3

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/

Stephan-v
  • 19,255
  • 31
  • 115
  • 201

3 Answers3

5

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);
}
btavares
  • 111
  • 1
  • 9
  • You are right, it will round to 135.3 which is not what was asked. Anyway, will leave it in case it is what someone else is looking for. – btavares Nov 09 '20 at 13:30
0

You could add a function checking if the number is an integer or not and use a condition within your localePrice function to apply your formatting (playing with slice to remove the decimal) :

function isInt(n) {
   return n % 1 === 0;
}

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


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

  if (isInt(amount)){
    return amount.toLocaleString(language, options).slice(0, -3);
  }
  else {
    return amount.toLocaleString(language, options);
  }
}

document.querySelector('.price').innerHTML = localePrice(135.21);

document.querySelector('.price-zeroes').innerHTML = localePrice(135.00);

document.querySelector('.price-with-one-zero').innerHTML = localePrice(135.30);
rabsom
  • 740
  • 5
  • 13
  • This will not work depending on the currency and language used. Some imply to have the current symbol appended after the number. – Laurent Mar 02 '20 at 19:36
  • Thing is the question is only about formating the number ;) – rabsom Apr 16 '20 at 07:55
0

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 })
Kochka
  • 113
  • 6