1

I have an Angular application which has an input field to enter number. I want to display the number with 3 decimal places if user enters any whole number. For example, if user enters 6, it should display as 6.000 as soon as user clicks outside the input field. Is there any angular way to do it?

Thanks

Kirti Jha
  • 93
  • 1
  • 3
  • 10

3 Answers3

0

You can use angular decimal pipe https://angular.io/api/common/DecimalPipe

valueVariable | number:'0.3-3'
zainhassan
  • 1,684
  • 6
  • 12
0

Use parse float with precision and use an event keyup or focusout to call a function to convert the number.

<input 
    (focusout)="convert($event.target.value)"
></input>
convert(num){
  this.num = parseFloat(num).toFixed(3); //where this.num is the variable for the said number.
}
kup
  • 731
  • 5
  • 18
0

You can use blue event in the input field like this:

<input (blur)='addDecimals()' [(ngModel)]="usernumber"/>

In your component do this:

public usernumber;

addDecimals() {
   this.usernumber.toFixed(3); // it will be a string
}

The best way to do this is using the decimal Pipe provided by angular, but how to use it is not provided in any answer. You should do this to get it working:

<input [ngModel]="item| number:'0.3-3' " 
      (ngModelChange)="item=$event" name="inputField" type="text" />

You can check here for more details, how to use it.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35