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
Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.
Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.
You can also use a decimal value: for example, a step of 0.3 will allow values such as 0.3, 0.6, 0.9 etc, but not 1 or 2. Now you don't get a validation error. Yay! Also note that if you only want to accept positive numbers, you'll want to add min=”0″.
AngularJS - Input number with 2 decimal places it could help... Filtering:
- 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".
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}
:
Credit due here and here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With