Format currency in JavaScript removing .00

Viewed 6340

I am currently formatting numbers to display as currency values using the following code:

return symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");

where symbol is £,$ etc. and value is a number with many decimal places. This works great but I now want to remove trailing .00 if present.

Currently I have this output:

1.23454 => £1.23
1 => £1.00
50.00001 => £50.00
2.5 => £2.50

I would like the following:

1.23454 => £1.23
1 => £1
50.00001 => £50
2.5 => £2.50

Is there a cleaner way than:

var amount = symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
return amount.replace(".00", "");

or is that solution the best way?

6 Answers

Look into Intl.NumberFormat. It is a very handy native api.

let number = 1.23454;

console.log(new Intl.NumberFormat('en-GB', {
  style: 'currency',
  currency: 'GBP'
}).format(number).replace(/(\.|,)00$/g, ''));
// → £1.23

You can get Intl.NumberFormat to round the currency to the nearest dollar (or pound or whatever) by setting maximumSignificantDigits to the number of digits in the integer part of your number

let number = 999.50;

console.log(new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumSignificantDigits: Math.trunc(Math.abs(number)).toFixed().length,
}).format(number));  // $1,000 (rounds up because 50 cents)

If you're using negative currencies, keep in mind that Intl.NumberFormat has the more sensible behavior of rounding away from zero as opposed to other JavaScript methods like Math.round. For example, Math.round(999.5) returns 1000 but Math.round(-999.5) returns -999 whereas using Intl.NumberFormat will return 1000 and -1000.

it can be done in a straightforward way

(parseFloat(percentage) / 100) * product.price)
    .toFixed(2)
    .toString()
    .replace('.00', '')

To remove trailing zeros in Intl.NumberFormat function I used this code:

let number = 50;
console.log(new Intl.NumberFormat('en-US', {
 style: 'currency',
 currency: 'USD',
 maximumSignificantDigits: (number + '').replace('.', '').length,
}).format(number)); // $50
Related