Reputation: 1445
So I know how to add a comma on numbers (toLocaleString.()) and this function requires integer or decimal value as a parameter. I need this result with 2 digit decimal value. It does run and return me correct data but I want decimal to be fixed to 2 digits like below
var num = 66666.7
console.log("original", num)
console.log("with comma", num.toLocaleString())
console.log("with 2 digit fixed", num.toFixed(2))
console.log("not working--", (num.toFixed(2)).toLocaleString())
console.log("error--", (num.toLocaleString()).toFixed(2))
Upvotes: 5
Views: 3104
Reputation: 986
I think toFixed() is changing the float to string.
num = 66666.7;
num = parseFloat(num.toFixed(2))
console.log(num.toLocaleString())
Following solution should work fine.
Edit - There is another solution for this
(Math.round(num * 100) / 100).toFixed(2);
Upvotes: 1
Reputation: 16301
The toFixed() method returns a string but the toLocaleString() method expects a number so just convert your string to a number after using the toFixed()
method with the parseFloat() function and then use the toLocaleString()
method on it.
However, do note that you will have to manually append the leading 0
since the parseFloat()
method removes any leading zeroes to the right of the decimal point.
Check this particular answer on another Stack Overflow thread that explains the reason why the parseFloat()
method removes the leading zeroes after the decimal point.
var num = 66666.7
var parsedNum = (""+num).split('.')[1].length > 1 ?
parseFloat(num.toFixed(2)).toLocaleString() :
parseFloat(num.toFixed(2)).toLocaleString() + '0';
console.log("original", num)
console.log("with comma", num.toLocaleString())
console.log("with 2 digit fixed", num.toFixed(2))
console.log("now working--", parsedNum)
Upvotes: 1
Reputation: 1586
You can specify the exact number of decimal digits in your options, which is the second parameter in toLocaleString()
const number = 24242324.5754;
number.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
// result is: 24,242,324.58
See also MDN doc here
minimumFractionDigits
The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is
maximumFractionDigits
The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3
Upvotes: 7