Display number always with 2 decimal places in <input>
AngularjsAngularjs Problem Overview
I have a float value for the ng-model that I would like to always display with 2 decimal places in the <input>
:
<input ng-model="myNumb" step ="0.01" type="number">
This works for most case when "myNumb" has decimal. But it will not force display of the 2 decimal places if "myNumb" has less than 2 decimal places (3.2), or an integer(30)
How can I force a display of 2 decimal place in the <input>
field
Angularjs Solutions
Solution 1 - Angularjs
AngularJS - Input number with 2 decimal places it could help... Filtering:
> 3. Set the regular expression to validate the input using ng-pattern. Here I want to accept only numbers with a maximum of 2 decimal places and with a dot separator.
<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal | number : 2" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />
Reading forward this was pointed on the next answer ng-model="myDecimal | number : 2".
Solution 2 - Angularjs
If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}
, as in:
<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>
BREAKDOWN
'1.2-2'
means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
:
- A minimum of 1 digit will be shown before decimal point
- It will show at least 2 digits after decimal point
- But not more than 2 digits
Solution 3 - Angularjs
> {{value | number : fractionSize}}
like {{12.52311 | number : 2}}
so this will print 12.52
Solution 4 - Angularjs
Simply use the number pipe like so :
{{ numberValue | number : '.2-2'}}
The pipe above works as follows :
-
Show at-least 1 integer digit before decimal point, set by default
-
Show not less 2 integer digits after the decimal point
-
Show not more than 2 integer digits after the decimal point
Solution 5 - Angularjs
Did you try using the filter
<input ng-model='val | number: 2'>
Solution 6 - Angularjs
Another shorthand to (@maudulus's answer) to remove {maxFractionDigits}
since it's optional.
You can use {{numberExample | number : '1.2'}}
Solution 7 - Angularjs
best way to Round off number to decimal places is that
a=parseFloat(Math.round(numbertobeRound*10^decimalplaces)/10^decimalplaces);
for Example ;
numbertobeRound=58.8965896589;
if you want 58.90
decimalplaces is 2
a=parseFloat(Math.round(58.8965896589*10^2)/10^2);
Solution 8 - Angularjs
Use currency filter with empty symbol ($)
{{val | currency:''}}