Angular Directive to round a decimal number

31,971

Solution 1

You can create two way binding conversion using directives. Here's a quick example:

app.directive('roundConverter', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl) {
      function roundNumber(val) {
        var parsed = parseFloat(val, 10);
        if(parsed !== parsed) { return null; } // check for NaN
        var rounded = Math.round(parsed);
        return rounded;
      }
      // Parsers take the view value and convert it to a model value.
      ngModelCtrl.$parsers.push(roundNumber);
   }
 };
});

http://plnkr.co/edit/kz5QWIloxnd89RKtfkuE?p=preview

It really depends on how you want it to work. Should it restrict user input? Do you mind having the model and view value differ? Should invalid number inputs be null on the model? These are all decisions for you to make. The directive above will convert invalid numbers to null.

Solution 2

You can use ngBlur and Math.round in an expression:

<input type="number" ng-model="number" ng-blur="number = Math.round(number)" />

Solution 3

<script>
      .controller('ExampleController', ['$scope', function($scope) {
  $scope.val = 1234.56789;
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter number: <input ng-model='val'></label><br>
  Default formatting: <span id='number-default'>{{val | number}}</span><br>
  No fractions: <span>{{val | number:0}}</span><br>
  Negative number: <span>{{-val | number:4}}</span>
</div>

OUTPUT: Enter number: 1234.56789

Default formatting: 1,234.568

No fractions: 1,235

Negative number: -1,234.5679

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

Share:
31,971
9blue
Author by

9blue

Updated on July 05, 2022

Comments

  • 9blue
    9blue about 2 years

    Does Angular have a built-in directive to round the input value?

    The number filter is not appropriate in this case because I want to round the actual val in ng-model as well. If I have to write one, what would it be like?