In order to ensure that all numbers are formatted according to our application language, I created a custom pipe where the locale and value are passed as parameters. This pipe functions similarly to the number pipe, but does not require the locale to be registered in the app.module file. The goal is to automatically format any numerical input when the user clicks outside of an edit modal field.
I have provided a functional example here: https://stackblitz.com/edit/decimal-pipe-comma-separator-example-arg-h3gtrw
For instance, if you enter 11111
in the input field, then click outside, you will see the input formatted as 111,11
. However, if you add .33
, it results in NaN (Not a Number).
How can I resolve this issue? One solution I considered was removing the thousand separators and keeping only the decimal separator before returning the transformed value in my number.pipe.ts
. But how do I determine the correct thousand separator for each locale? For example, in EN
it's ,
, while in DE
it's .
. Is there a function to retrieve the separator based on the locale?
//pipe
*/
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberFormat'
})
export class NumberFormatPipe implements PipeTransform {
transform(value: number | string, minFractionDigits: number = 0, maxFractionDigits: number = 2, locale: string = 'en'): string {
return new Intl.NumberFormat(locale, {
minimumFractionDigits: minFractionDigits,
maximumFractionDigits: maxFractionDigits
}).format(Number(value));
}
}
<div>
<input type="text" [ngModel]="userNum | numberFormat"
(ngModelChange)="userNum=$event" [ngModelOptions]="{updateOn:'blur'}">
</div>