tags:

views:

103

answers:

4

How do you format a number to show 2 decimals in JavaScript?

Something along the lines of: format(x,"9,999.99");

A: 

I'm not sure if you are trying to do this to input or just for displaying text on the page. You can use the masked input plugin for jQuery if you are trying to format input.

http://digitalbush.com/projects/masked-input-plugin/

Climber104
I don't think this is what he wanted, I suppose psenn wants to specify the number of decimals
Fabien Ménager
+2  A: 
var num = 3.14159;
var fixed = num.toFixed(2);

If you want the commas depending on the locale:

var localed = num.toLocaleString();

Combining both crudely:

var num = 3.14159;
var fixed = num.toFixed(2);
var fixednum = parseFloat(fixed);
var localedFixed = fixednum.toLocaleString();
strager
+2  A: 

You should use this :

x.toFixed(2);

or if you want to be sure it will work :

parseFloat(x).toFixed(2);
Fabien Ménager
`toFixed` doesn't comma format.
Crescent Fresh
I had to use parseFloat first because JavaScript wasn't recognizing my numbers as numeric.
cf_PhillipSenn
+2  A: 

Use .toFixed(2):

http://www.devguru.com/technologies/javascript/17443.asp

Note this will round your number:

var i = 23.778899;
alert(i.toFixed(2));

gives you

23.78
RedFilter
`toFixed` doesn't comma format.
Crescent Fresh
@crescentfresh, The question didn't specifically ask for it.
strager