在 < input > 中始终显示小数点后2位的数字

我有一个 ng-model 的浮点值,我希望在 <input>中始终显示小数点后两位的值:

<input ng-model="myNumb" step ="0.01" type="number">

当“ myNumb”具有小数时,这在大多数情况下都适用。但是,如果“ myNumb”的小数位数小于2(3.2)或整数(30) ,则不会强制显示小数位数为2的内容
如何在 <input>字段中强制显示小数点后2位

353671 次浏览

AngularJS - Input number with 2 decimal places it could help... Filtering:

  1. 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".

Did you try using the filter

<input ng-model='val | number: 2'>

https://docs.angularjs.org/api/ng/filter/number

Use currency filter with empty symbol ($)

\{\{val | currency:''}}
\{\{value | number : fractionSize}}

like \{\{12.52311 | number : 2}}

so this will print 12.52

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

Credit due here and here

Another shorthand to (@maudulus's answer) to remove {maxFractionDigits} since it's optional.

You can use \{\{numberExample | number : '1.2'}}

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);

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

(Math.round(2.782061* 100 )/100).toFixed(2);

This will convert that into Two decimal places: For Ex: 2.782061 ---> 2.78 two decimal Places