Search code examples
javascriptformattingnumberslocalecurrency

toLocaleString price without decimal zeroes


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/


Solution

  • 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);