I am displaying currency values in javascript, I want to display $ with every value and I also want , (comma) for thousands but I don't want rounding of digits after decimal point and I also don't have a fixed limit of how many digits would be after decimal point.
It is for en-AU
for example
45000 -> $45,000
3.6987 -> $3.6987
3 -> $3
4.00 -> $4.00
Is there any built-in JavaScript method or library can help to achieve this?
I Suggest to use Intl.NumberFormat
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
});
formatter.format(3242); /* $3,242.00 */
You can config your FractionDigits and even your currency sign :
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 4,
});
formatter.format(3242); /* £3,242.0000 */
UPDATE :
if you can't fixed your fraction digits you can use maximumFractionDigits and give it an amount of 20 and also give minimumFractionDigits value of 0 :
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 0,
maximumFractionDigits: 20,
});
formatter.format(3242.5454); /* £3,242.5454 */
You can use toLocaleString to add the commas to the number.
var number = 45000;
var formatted = '$' + number.toLocaleString(); // $45,000
number = 500999.12345;
formatted = '$' + number.toLocaleString(); // $500,999.12345
EDIT: To prevent rounding, use minimumFractionDigits option:
number.toLocaleString(undefined, { minimumFractionDigits: 20 });
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Related to this question.
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