Intl.NumberFormat either 0 or two fraction digits

You could try something like this:

formatter.format(amount).replace(/\D00$/, '');

Update:

In response to the many-months-later comment by @Marek, the above regex already handles differing decimal symbols (either . or ,), but it's true that it doesn't handle trailing currency symbols. That can be fixed this way:

formatter.format(amount).replace(/\D00(?=\D*$)/, '');

The correct way to do it when using Intl.NumberFormat is to set both maximumFractionDigits and minimumFractionDigits options in constructor while validating input value using a modulo % for a whole number (per https://stackoverflow.com/a/49724586/1362535 which is a CORRECT answer!). The accepted answer is sort of string manipulation.

const fraction = new Intl.NumberFormat('en-NZ', {
  style: 'currency',
  currency: 'NZD',
  minimumFractionDigits: 0,
  maximumFractionDigits: 0,
});

const formatter = new Intl.NumberFormat('en-NZ', {
  style: 'currency',
  currency: 'NZD',
  minimumFractionDigits: 2,
});

let number = 4.1;
  if(number % 1 == 0)
console.log(fraction.format(number));
  else
console.log(formatter.format(number));

number = 4;
  if(number % 1 == 0)
console.log(fraction.format(number));
  else
console.log(formatter.format(number));

I would implement two different formats and validate it using a modulo %

4 % 1 == 0
4.1 % 1 == .1

Hope this helps :)

const formatter = new Intl.NumberFormat('en-NZ', {
  style: 'currency',
  currency: 'NZD',
  minimumFractionDigits: 2,
});

const fraction = new Intl.NumberFormat('en-NZ', {
  style: 'currency',
  currency: 'NZD',
  minimumFractionDigits: 0,
});


let number = 4.1;
  if(number % 1 == 0)
console.log(fraction.format(number));
  else
console.log(formatter.format(number));


number = 4;
  if(number % 1 == 0)
console.log(fraction.format(number));
  else
console.log(formatter.format(number));

Tags:

Javascript