Imran Shaikh
Imran Shaikh

Reputation: 11

Angularjs Directive Roundoff two digit after decimal

I want to create a directive, that will round off the two digit values after decimal.

For example:

10.456456 should be 10.46

10.3633 should be 10.34

This is what I have tried so far, but it's not working.

marineQuote.directive('roundConverter2', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModelCtrl) {
            function roundNumber(input, places) {
                if (isNaN(input)) return input;
                var factor = "1" + Array(+(places > 0 && places + 1)).join("0");
                return Math.round(input * factor) / factor;
            }
            ngModelCtrl.$parsers.push(roundNumber); 
        }
    };
});

HTML:

<td><input type="text" name="claimsLR1" ng-disabled="true"
  ng-model="premiumCalculations.percentage1" round-converter2=''></td>

Upvotes: 1

Views: 670

Answers (1)

Avnesh Shakya
Avnesh Shakya

Reputation: 3906

Try this:

return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl) {
        function roundNumber(input, places) {
            if (isNaN(input)) return input;
            return parseFloat(input).toFixed(2);
        }
        ngModelCtrl.$parsers.push(roundNumber);
    }
};

Hope this will work for you.

Upvotes: 1

Related Questions