'Format currency in JavaScript removing .00

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?



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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

Please change the value to test

Solution 4:[4]

As suggested by @RobG, I can use:

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

Solution 5:[5]

it can be done in a straightforward way

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

Solution 6:[6]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Ghanshyam Dekavadiya
Solution 4
Solution 5 S.Sid
Solution 6 marouan azizi