2

In my code I have something like this here:

var myNumber: number = 1.0;

However angular automatically removes the zero in my respective form. I could make it a string but that seems like an odd solution.

How can I tell Angular that it should also display the zero and not remove it?

Miger
  • 1,175
  • 1
  • 12
  • 33
  • that's exactly how javascript works (there is only one `number` type). To see this open your developer JS console with F12 and just write `console.log(1.0)`. You want to format the display of your number. What I mean by my comment, is that any solution, would it be Angular specific or general Javascript would work. – Pac0 Sep 25 '18 at 14:09
  • Possible duplicate of [Angular how to display number always with 2 decimal places in ](https://stackoverflow.com/questions/35513413/angular-how-to-display-number-always-with-2-decimal-places-in-input) – Michael W. Czechowski Sep 25 '18 at 14:09
  • But that function is still there: https://angular.io/api/common/DecimalPipe – Michael W. Czechowski Sep 25 '18 at 14:12
  • @MichaelCzechowski you are right. I removed my comment (though I'm uncomfortable voting for this duplicate target anyway) – Pac0 Sep 25 '18 at 14:12
  • You can use DecimalPipe as said above https://stackblitz.com/edit/date-pipe-angular?file=src%2Fapp%2Fapp.component.html – Amit Chigadani Sep 25 '18 at 14:14
  • can't you use `{{myNumber.toFixed(1)}}`? – Ali Shahbaz Sep 25 '18 at 14:21

3 Answers3

3

You can do this using DecimalPipe

{{myNumber | number : '1.1-1'}}

Parameters of pipe explained here in docs

Decimal representation options, specified by a string in the following format: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}.

  1. minIntegerDigits: The minimum number of integer digits before the decimal point. Default is 1.
  2. minFractionDigits: The minimum number of digits after the decimal point. Default is 0.
  3. maxFractionDigits: The maximum number of digits after the decimal point. Default is 3.

Demo

Community
  • 1
  • 1
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
1

Have a look at DecimalPipe. Add inside your template kind of that here:

{{ value_expression | number }}

This will cause to display the number as it is definde.

Michael W. Czechowski
  • 3,366
  • 2
  • 23
  • 50
1

Use the DecimalPipe as follows:

{{ myNumber | number:'1.1-1' }}

This says:

Make sure there is at least 1 (the 1st one) number before the decimal place and

Between 1 (the 2nd one) and 1 (the 3rd one) numbers after the decimal place

danday74
  • 52,471
  • 49
  • 232
  • 283