How to remove null decimal part (00) of Javascript number formatting?

Asked

Viewed 36 times

1

I intend in Javascript to have the following result:

Entree Expected exit
1.6 1,60€
1 1€
1.55 1,55€

I’ve tried to:

num.toLocaleString('pt-PT', {
  minimumFractionDigits: 0,
  maximumFractionDigits: 2
}) + '€';

But unsuccessfully, since, for input 1.6, receiving 1,6€, where I wish for two decimal digits in this type of scenario.

  • If you are not going to change the format (at least this is what appears in the table), wouldn’t it be simpler just to concatenate the "€"? if you have "1.55" and want to return the same format I don’t understand why use the toLocaleString

  • @Ricardopontual, the toLocaleString is probably to format the number correctly according to the standard pt-PT. See that 12345.67 is different from 12 345,67 (formatting result).

  • yes, but for what it has examples is not necessary, hence my doubt :)

  • 1

    @Ricardopunctual, it was my mistake in the edition, I just saw it now, thank you! : ) In fact the original examples showed that yes.

  • I need to format, for the pt_EN currency, if the decimal separator is a point it has to be a comma

1 answer

2


The simplest answer is to remove the ,00 manually in case it exists, since there is no format option that covers that format.

function fmt(num) {
  return num
    .toLocaleString('pt-PT', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    })
    .replace(/,00$/, '') + '€';
}

console.log(fmt(1));
console.log(fmt(1.2));
console.log(fmt(1.23));

Note that if formatting is too frequent, it might be worth using a "specialized" API instance Intl.NumberFormat.

  • I’ll take a look Intl.Numberformat, but your solution solved the problem for now, thank you

  • 1

    Can avoid using replace, return num.toLocaleString('pt-PT', {minimumFractionDigits: "0", style:"currency", currency: "EUR", currencyDisplay: "symbol"});

  • 1

    @Augustovasques, I thought about it, but in this case, 1.1 would not be 1,10€, but yes 1,1 €. As far as I can see, it really looks like an extremely customized format that escapes from the same patterns...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.