Search code examples
javascriptstringformatcurrency-formatting

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

  • 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