5

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Janey
  • 1,260
  • 3
  • 17
  • 39

2 Answers2

7

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.

AngularJS application

var app = angular.module('plunker', ['ng-currency']);

app.controller('ApplicationController', function($scope) {
  $scope.amount = '0.203';
});

View

<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

lin
  • 17,956
  • 4
  • 59
  • 83
3

Error: ngModel:numfmt Model is not of type number

You should parse scope.theItem.charge value to float - toFixed returns string:

$scope.theItem.charge = parseFloat(parseFloat(10 * 2).toFixed(2));

Yes, this is ugly... :)

You can also write directive for parsing string to float:

directive('parseFloat', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(value) {
        return '' + value;
      });
      ngModel.$formatters.push(function(value) {
        return parseFloat(value);
      });
    }
  };
});

And simply use this directive on input field:

<input type="number" name="charge" id="charge" ng-model="theItem.charge" step="0.01" parseFloat>
Krzysztof Raciniewski
  • 4,735
  • 3
  • 21
  • 42