I'm trying to create a function with javascript that displays all numbers with two decimal points and adds commas every three digits (1,000 10,000 100,000 etc).
At first I had this:
var formatNumber = function(num) {
return parseFloat((num).toFixed(2)).toLocaleString();
};
This works very well but with one exception.
1.2 != 1.20 in the final output. It just shows up as 1.2
But everything else is good. 124.5879697 = 124.59, 10000 = 10,000, and 10586.357 = 10,586.36
The issue is the final output is going to display as money, so displaying 10000 as $10,000 is fine. But displaying 1.2 as $1.2 looks a little off.
To get around this I tried to add the following modification:
var formatNumber = function(num) {
return parseFloat((Math.round(num*100)/100)).toFixed(2).toLocaleString();
};
This carries everything out to two decimal places, which is fine, but it seems to have de-activated toLocaleString because now nothing displays commas.
I'm looking to use pure Javascript with this and not jQuery. It seems there are a lot of js questions on this topic about one or the other issue, but not combining both.
Thank you.
This seems to work
var formatNumber = function(num) {
return parseFloat(num).toFixed(2).toLocaleString();
};
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