Question

I have an ng-change that updates a text input based on the text entered into another input - https://stackoverflow.com/questions/22256174/angularjs-want-to-show-1-x-in-a-text-input-when-the-users-sets-a-value-0

However the value that is being set with ng-change should only be displayed in steps of 0.01. That is, two decimal places. But due to Chrome not 'fixing' floating point rounding errors for display, sometimes the text input shows values like 0.19999999996.

I was thinking the AngularJS number filter could be of use but adding it inside ng-change isn't working for me -

ng-change="v1 = 1 - v2 | number:2"

Is it possible to get this to work?...or is there some other workaround?

Was it helpful?

Solution

You can use the $filter service in your controller:

$filter('number')(number, fractionSize)

For example:

app.controller('MyCtrl', ['$scope', '$filter',
  function MyCtrl($scope, $filter) {

    $scope.change = function() {
      $scope.v1 = $filter('number')(1 - $scope.v2, 2);
    };
  }
]);

And:

<body ng-controller="MyCtrl">
  <input ng-model="v2" ng-change="change()" />
  <input ng-model="v1" />
</body>

Demo: http://plnkr.co/edit/lUVyAL8nuCPKM66I7J0W?p=preview

Updated demo: http://plnkr.co/edit/f8UZQY3d4YF4LFd3FvoF?p=preview

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top