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"
The Intl. NumberFormat object enables language-sensitive number formatting.
The maximum number of significant digits for the number formatter.
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.
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.
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));
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*$)/, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With