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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With