iChido iChido - 4 months ago 23
AngularJS Question

AngularJS currency filter: can I remove the .00 if there are no cents in the amount?

I am following this: http://docs.angularjs.org/api/ng.filter:currency
When I type 1234.56 in the field then the output should be $1,234.56. But if I type in the input 1234 then the output is $1,234.00. I don't want the decimal and the zeros to appear.
How can this be done?

jdp jdp
Answer

Add a new filter:

'use strict';

angular
    .module('myApp')
    .filter('myCurrency', ['$filter', function($filter) {
        return function(input) {
            input = parseFloat(input);
            input = input.toFixed(input % 1 === 0 ? 0 : 2);
            return '$' + input.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        };
    }]);

In your view:

<span>{{ '100' | myCurrency }}</span> <!-- Result: $100 -->
<span>{{ '100.05' | myCurrency }}</span> <!-- Result: $100.05 -->
<span>{{ '1000' | myCurrency }}</span> <!-- Result: $1,000 -->
<span>{{ '1000.05' | myCurrency }}</span> <!-- Result: $1,000.05 -->
Comments