Removing AngularJS currency filter decimal/cents

AngularjsFilterFormattingAngularjs Filter

Angularjs Problem Overview


Is there a way to remove the decimal/cents from the output of a currency filter? I'm doing something like this:

<div>{{Price | currency}}</div>

Which outputs:

>$1,000.00

Instead, I'd like:

>$1,000

Can that be done using the currency filter? I know I can prepend a dollar sign onto a number, and I could write my own filter, but I was hoping a simple method exists with the existing currency filter.

Thank you.

Angularjs Solutions


Solution 1 - Angularjs

Update: as of version 1.3.0 - currencyFilter: add fractionSize as optional parameter, see commit and updated plunker

{{10 | currency:undefined:0}}

Note that it's the second parameter so you need to pass in undefined to use the current locale currency symbol

Update: Take note that this only works for currency symbols that are displayed before the number. As of version 1.2.9 it's still hardcoded to 2 decimal places.

Here is a modified version that uses a copy of angular's formatNumber to enable 0 fractionSize for currency.


Normally this should be configurable either in the locale definition or the currencyFilter call but right now(1.0.4) it's hardcoded to 2 decimal places.

Custom filter:

myModule.filter('noFractionCurrency',
  [ '$filter', '$locale',
  function(filter, locale) {
    var currencyFilter = filter('currency');
    var formats = locale.NUMBER_FORMATS;
    return function(amount, currencySymbol) {
      var value = currencyFilter(amount, currencySymbol);
      var sep = value.indexOf(formats.DECIMAL_SEP);
      if(amount >= 0) { 
        return value.substring(0, sep);
      }
      return value.substring(0, sep) + ')';
    };
  } ]);

Template:

<div>{{Price | noFractionCurrency}}</div>

Example:

Update: fixed a bug when handling negative values

Solution 2 - Angularjs

The question seems to be pretty old and the given answers are nice. However, there is another alternative solution which can also help (which I use in my projects).

This is working very well with currency symbols prefixing as well as suffixing the number for positive and negative values.

Custom filter:

angular.module('your-module', [])
    .filter('nfcurrency', [ '$filter', '$locale', function ($filter, $locale) {
        var currency = $filter('currency'), formats = $locale.NUMBER_FORMATS;
        return function (amount, symbol) {
            var value = currency(amount, symbol);
            return value.replace(new RegExp('\\' + formats.DECIMAL_SEP + '\\d{2}'), '')
        }
    }])

Template:

<div>{{yourPrice| nfcurrency}}</div>

Examples for different locales:

  • 10.00 (en-gb) -> £10
  • 20.00 (en-us) -> $20
  • -10.00 (en-us) -> ($10)
  • 30.00 (da-dk) -> 30 kr
  • -30.00 (da-dk) -> -30 kr

Please have a look at live demo for US dollars and Danish Krone.

Update

Please note that this workaround is good for AngularJS 1.2 and earlier releases of the library. As of AngularJS 1.3 you can use currency formatter with third parameter specifying fraction size - "Number of decimal places to round the amount to".

Note that in order to use default currency format coming from AngularJS localization, you would have to use currency symbol (second parameter) set to undefined (null or empty will NOT work). Example in demos for US dollars and Danish Krone.

Solution 3 - Angularjs

Another thing that is worth considering is if you know you only have one locale or one type of currency, you could put the currency symbol before the number and then use the number filter like so (for US currency).

  ${{Price | number:0}}

More of a quick fix solution if you don't want to throw in a new filter and only have one currency.

Solution 4 - Angularjs

It's late but might be it can help some one

{{value | currency : 'Your Symbol' : decimal points}}

So let's see some examples with output

{{10000 | currency : "" : 0}}           // 10,000
{{10000 | currency : '$' : 0}}          // $10,000 
{{10000 | currency : '$' : 2}}          // $10,000.00 
{{10000 | currency : 'Rs.' : 2}}        // Rs.10,000.00
{{10000 | currency : 'USD $' : 2}}      // USD $10,000.00
{{10000 | currency : '#' : 3}}          // #10,000.000
{{10000 | currency : 'ANYTHING: ' : 5}} // ANYTHING: 10,000.00000

See the demo

Solution 5 - Angularjs

This is another similar solution, but it removes .00 decimal, but leaves any other decimal amount.

$10.00 to $10

$10.20 to $10.20

app.filter('noFractionCurrency', [ '$filter', '$locale', function(filter, locale) {
    var currencyFilter = filter('currency');
    var formats = locale.NUMBER_FORMATS;
    return function(amount, currencySymbol) {
        amount = amount ? (amount*1).toFixed(2) : 0.00;
        var value = currencyFilter(amount, currencySymbol);
        // split into parts
        var parts = value.split(formats.DECIMAL_SEP);
        var dollar = parts[0];
        var cents = parts[1] || '00';
            cents = cents.substring(0,2)=='00' ? cents.substring(2) : '.'+cents; // remove "00" cent amount
        return dollar + cents;
    };
}]);

Solution 6 - Angularjs

Solution for angular version < 1.3, if you use i18n the simplest way is:

$filter('number')(x,0) + ' ' +$locale.NUMBER_FORMATS.CURRENCY_SYM;

This way you have the number formatted with correct separators and currency symbol based on locale.

Solution 7 - Angularjs

Another solution, this one removes the trailing zeros and finds the proper currency symbol for the most common currencies:

{{10.00|money:USD}} to $10

{{10.00|money:EUR}} to €10

/**
 * @ngdoc filter
 * @name money
 * @kind function
 *
 * @description
 * Formats a number as a currency (ie $1,234.56), removing trailing zeros and using the     real currency symbol when possible. When no currency symbol is provided, default
 * symbol for current locale is used.
 *
 * @param {number} amount Input to filter.
 * @param {string=} symbol Currency symbol or identifier to be displayed.
 * @returns {string} Formatted number. *
 */
app.filter('money', [ '$filter', '$locale', function (filter, locale) {
var currencyFilter = filter('currency');
var formats = locale.NUMBER_FORMATS;

var getCurrencySymbol = function (code) {
    switch (code.toUpperCase()) {
        case 'EUR': //Euro
            return '€';

        case 'USD': //Dólar americano
        case 'MXN': //Peso mejicano
        case 'CAD': //Dólar de Canadá
        case 'AUD': //Dólar australiano
        case 'NZD': //Dólar neozelandés
        case 'HKD': //Dólar de Hong Kong
        case 'SGD': //Dólar de Singapur
        case 'ARS': //Peso argentino
            return '$';

        case 'CNY': //Yuan chino
        case 'JPY': //Yen japonés
            return '¥';

        case 'GBP': //Libra esterlina
        case 'GIP': //Libras de Gibraltar
            return '£';

        case 'BRL': //Real brasileño
            return 'R$';

        case 'INR': //Rupia india
            return 'Rp';

        case 'CHF': //Franco suizo
            return 'Fr';

        case 'SEK': //Corona sueca
        case 'NOK': //Corona noruega
            return 'kr';

        case 'KPW': //Won de Corea del Norte
        case 'KRW': //Won de Corea del Sur
            return '₩';

        default:
            return code;
    }
};

return function (amount, currency) {
    var value;
    if (currency) {
        value = currencyFilter(amount, getCurrencySymbol(currency));
    }
    else {
        value = currencyFilter(amount);
    }

    //Remove trailing zeros
    var regex = new RegExp("\\" + formats.DECIMAL_SEP + "0+", "i");
    return value.replace(regex, '');
};
} ]);

Solution 8 - Angularjs

And here if you want to round up to nearest $1000: Live Demo:

var app = angular.module('angularjs-starter', []);

app.filter('noFractionRoundUpCurrency',
    [ '$filter', '$locale', function(filter, locale) {
      var currencyFilter = filter('currency');
      var formats = locale.NUMBER_FORMATS;
      return function(amount, currencySymbol) {
        var value = currencyFilter(amount, currencySymbol);
        var sep = value.indexOf(formats.DECIMAL_SEP);
        if(amount >= 0) { 
                    if (amount % 1000 < 500){
                        return '$' + (amount - (amount % 500));
                    } else {
                        return '$' + (amount - (amount % 500) + 500);          
                    }
          
        }
        else{
                    if (-amount % 1000 < 500){
                        return '($' + (-amount - (-amount % 500)) + ')';
                    } else {
                        return '($' + (-amount - (-amount % 500) + 500)+ ')';          
                    }
        }
      };
    } ]);
    
app.controller('MainCtrl', function($scope) {

});

Solution 9 - Angularjs

Exactly what I needed!

I added a conditional to just replace Angular's currency filter altogether and just use a modified version of the filter seen above by @Tom. I'm sure there are better ways to do this but it seems to work well for me thus far.


'use strict';
angular.module('your-module')
.filter('nfcurrency', [ '$filter', '$locale', function ($filter, $locale) {
var currency = $filter('currency'), formats = $locale.NUMBER_FORMATS;
return function (amount, symbol) {
var value = currency(amount, symbol), valArr = value.split(formats.DECIMAL_SEP);
if(parseInt(valArr[(valArr.length - 1)]) > 0) {
return value;
} else {
return value.replace(new RegExp('\' + formats.DECIMAL_SEP + '\d{2}'), '');
}
};
}]);

Solution 10 - Angularjs

I have modified a bit the filter posted by @Liviu T. to accept currencies with symbol after the number and certain number of decimals:

app.filter('noFractionCurrency',
[ '$filter', '$locale', function(filter, locale) {
  var currencyFilter = filter('currency');
  var formats = locale.NUMBER_FORMATS;
  return function(amount, num, currencySymbol) {
    if (num===0) num = -1;
    var value = currencyFilter(amount, currencySymbol);
    var sep = value.indexOf(formats.DECIMAL_SEP)+1;
    var symbol = '';
    if (sep<value.indexOf(formats.CURRENCY_SYM)) symbol = ' '+formats.CURRENCY_SYM;
    return value.substring(0, sep+num)+symbol;
  };
} ]);

For example:

{{10.234 | noFractionCurrency:0}}
{{10.55555 | noFractionCurrency:2}}

Outputs:

$10
$10.56

Demo

Solution 11 - Angularjs

If you'd use angular-i18n (bower install angular-i18n), you could use a decorator to change the defaults in the locale files, like so:

$provide.decorator('$locale', ['$delegate',
  function ($delegate) {
    $delegate.NUMBER_FORMATS.PATTERNS[1].maxFrac = 0;
    $delegate.NUMBER_FORMATS.PATTERNS[1].minFrac = 0;
    return $delegate;
}]);

Note that this would apply to all currency filter uses in your code.

Solution 12 - Angularjs

In Angular 4+

{{totalCost | currency : 'USD' : 'symbol' : '1.0-0' }}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike PaterasView Question on Stackoverflow
Solution 1 - AngularjsLiviu T.View Answer on Stackoverflow
Solution 2 - AngularjsTomView Answer on Stackoverflow
Solution 3 - AngularjsJM HuretView Answer on Stackoverflow
Solution 4 - AngularjsAli AdraviView Answer on Stackoverflow
Solution 5 - AngularjsDustinView Answer on Stackoverflow
Solution 6 - AngularjsAndreiCView Answer on Stackoverflow
Solution 7 - AngularjsJavier MarínView Answer on Stackoverflow
Solution 8 - AngularjsDavid DehghanView Answer on Stackoverflow
Solution 9 - AngularjsSmcculloughView Answer on Stackoverflow
Solution 10 - AngularjsbertslikeView Answer on Stackoverflow
Solution 11 - AngularjsDormouseView Answer on Stackoverflow
Solution 12 - AngularjsAndrew KoperView Answer on Stackoverflow