I have an issue with displaying form data fields to 2 decimal places. I set the variable $Scope.theItem.Charge
to 2 decimal places:
$scope.theItem.charge = parseFloat(10 * 2).toFixed(2);
I then display this data in an editable form field like this:
<input type="text" name="charge" id="charge" ng-model="theItem.charge">
This works correctly and displays the result, which in this case is 20.00
.
However, because we are saying that this is an input type of "text" the user is able to enter any text into the field, not just numbers. I’d expect to simply do this:
<input type="number" name="charge" id="charge" ng-model="theItem.charge" step="0.01">
But that returns the following error:
angular.min.js:119 Error: [ngModel:numfmt]
http://errors.angularjs.org/1.5.9/ngModel/numfmt?p0=25.00
at angular.min.js:6
at Array. (angular.min.js:182)
at angular.min.js:293
at m.$digest (angular.min.js:144)
at m.$apply (angular.min.js:147)
at l (angular.min.js:98)
at D (angular.min.js:103)
at XMLHttpRequest.w.onload (angular.min.js:104)
Does anyone have any ideas on how to resolve this? I’ve tried to use the angular directive as described in the link above but that does not work for my scenario.
We use ng-currency to handle this problem. It seems to be the most stable way to handle decimals in input fields. ng-currency
does validate and normalize your ng-model
in a nice way. So you don't need to fight with fractions or wrong user input data anymore. Please check this demo plnkr.
var app = angular.module('plunker', ['ng-currency']);
app.controller('ApplicationController', function($scope) {
$scope.amount = '0.203';
});
<div class="container" ng-controller="ApplicationController">
<div class="row">
<input type="text"
ng-model="amount"
currency-symbol=""
ng-currency
fraction="2" />
</div>
</div>
--> Demo plnkr
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