Search code examples
angularangular6angular-pipe

format a number with double precision angular


I need to load a number in input form but there is some problem when I format the number. In details the number can be :

1.99
15.00
230.88
2,999.00
etc

I use this code:

 [ngModel]="price |  number : '1.2-2' "

but it gives me this warning:

The specified value "1,333.00" is not a valid number.

I use Angular 6. Anyone can help me?


Solution

  • The first problem is caused by the comma. For any other reason another problem is that number : '1.2-2' does not take values larger 3 digits before comma.

    I have create a stackblitz to show a possible solution:

    <input type="number" [ngModel]="price | toNumber "/>
    

    Use a custom pipe to replace the , and to ensure number : '1.2-2' still valid. You can extend it by your need to solve any problem.

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'toNumber'
    })
    export class ToNumberPipe implements PipeTransform {
      transform(value: string):any {
        let retNumber = parseFloat(parseFloat(value.replace(/,/g, '')).toFixed(2))
        return isNaN(retNumber) ? 0 : retNumber;
      }
    }
    

    Advantage of custom pipe solution: You can customize your behavior. number : '1.2-2' unfortunately rounds the number, and even worse, there's no word about it in the documentation (found in the comments of this answer: https://stackoverflow.com/a/38478060/3623608)