toLocaleString price without decimal zeroes

Viewed 3368

I am wondering how to efficiently remove the decimal zeroes from a price while keeping the 2 decimals if there

So if a price is 135.00 it should become 135.

If a price is 135.30 however it should keep both decimals.

If a price is 135.38 it can keep the decimals.

This is what I have at the moment:

const currency = 'EUR';
const language = 'NL';

var localePrice = (amount) => {
  const options = {
    style: 'currency',
    currency: currency
  };

  return amount.toLocaleString(language, options);
}

Now I could use regex or something similar but I am hoping there is an easier way to get this done.

I have made a JSFiddle which illustrates my problem which makes it easy to play with the code.

https://jsfiddle.net/u27a0r2h/2/

3 Answers

Try just add minimumFractionDigits: 0 to your options, like:

const currency = 'EUR';
const language = 'NL';

var localePrice = (amount) => {
  const options = {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: 0
  };

  return amount.toLocaleString(language, options);
}

The first answer using minimumFractionDigits is the good approach, just set it to 0 or 2 depending on the case.

amount = 5.20
amount.toLocaleString('fr-FR', { style: 'currency', 
                                 currency: 'EUR', 
                                 minimumFractionDigits: Math.ceil(amount % 1) * 2 })
Related