Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intl.NumberFormat either 0 or two fraction digits

Tags:

javascript

My formatter looks like this

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

How can I adjust this so that whole numbers have 0 fraction digits

formatter.format(4); // want output "$4" 

whilst fractions always show two digits?

formatter.format(4.1); // want output "$4.10" 
like image 728
alt Avatar asked Apr 09 '18 01:04

alt


People also ask

What is Intl NumberFormat?

The Intl. NumberFormat object enables language-sensitive number formatting.

What is Maximumsignificantdigits?

The maximum number of significant digits for the number formatter.

What is minimumFractionDigits?

minimumFractionDigits is the minimum number of fraction digits to use, ranging from 0 to 20. The default is 0 for plain number and percent formatting. The default for currency formatting is specified by the ISO 4217 currency code list, and 2 if it's not specified in the list.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.


2 Answers

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));
like image 113
crtag Avatar answered Sep 29 '22 15:09

crtag


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*$)/, ''); 
like image 28
kshetline Avatar answered Sep 29 '22 16:09

kshetline