9blue
9blue

Reputation: 4753

Angular Directive to round a decimal number

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?

Upvotes: 2

Views: 33227

Answers (3)

Kelash Kumar Khatri
Kelash Kumar Khatri

Reputation: 31

<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

Upvotes: 2

Adam
Adam

Reputation: 1143

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.

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

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

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

Upvotes: 6

Related Questions