Multitut
Multitut

Reputation: 2169

Angular: Better way to limit number to two decimals on input?

I am working on an Angular 4 app where i need to show amounts on inputs, these amounds have usually more than two decimals i.e. 34.3899019 but I need to show only the first two decimals: 34.38.

I have managed to do so by creating my own pipe:

import {Pipe, PipeTransform} from "@angular/core";

@Pipe({ name: 'TrimDecimalPipe'})
export class TrimDecimalPipe implements PipeTransform{
    transform(val) {
        return val.toFixed(2);
    }
}

And using it like this:

<input type="number" [ngModel]="payment.card.Amount | TrimDecimalPipe" (ngModelChange)="payment.card.Amount=$event" class="form-control" />

Something important: this input has to implement two way data binding such as my html example or [(ngModel)].

This works but it messes up when I try to modify the amount on the input, maybe because of my pipe reacting as I type.

Upvotes: 1

Views: 10246

Answers (2)

Garth Mason
Garth Mason

Reputation: 8001

I agree with @DeborahK re: pipes for displaying the values.

You could also consider not using a pipe in this case, and rather rounding the value to two-decimal places after the user input finishes via binding to the blur event.

E.g. in the template

<input type="number" [(ngModel)]="myValue" (blur)="onBlur($event)"/>

And in the component ..

onBlur(evt){
    if(evt.target.valueAsNumber){
      this.myValue = evt.target.valueAsNumber.toFixed(2);
   }
}     

Upvotes: 0

DeborahK
DeborahK

Reputation: 60518

There is already a built-in decimal pipe to do this for you:

https://angular.io/api/common/DecimalPipe

But as you found, they don't work with two-way binding.

Thee is a discussion using the format you are using here: Using Pipes within ngModel on INPUT Elements in Angular2-View

Personally, I'd use the built-in decimal pipe for displaying the value as you need. But let the user type in whatever format they'd like. Trying to format as someone types always leads to odd edge cases, such as when they try to delete a character.

Upvotes: 2

Related Questions