Reputation: 1235
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?
Upvotes: 3
Views: 10764
Reputation: 584
This worked for me: You need to truncate.
var num = parseFloat( 15.7784514 );
var formatted = new Intl.NumberFormat("en-US", {style: "currency", currency: "USD", roundingMode: "trunc"}).format(v)
Upvotes: 1
Reputation: 439
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 });
Related to this question.
Upvotes: 4
Reputation: 3451
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 */
Upvotes: 7
Reputation: 1839
Take a look at accounting.js, it has great features for formatting value in currency format.
Upvotes: 1