Format a number to two decimal places

ma11hew28 picture ma11hew28 · Jan 6, 2011 · Viewed 28.9k times · Source

Give me a native (no jQuery, Prototype, etc. please) JavaScript function that converts numbers as follows:

input:  0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5
output: 0.39, 2.50, 4.25, 5.50, 6.75, 7.75, 8.50

E.g., in Ruby, I'd do something like this:

>> sprintf("%.2f", 2.5)
=> "2.50"

The output may be a number or a string. I don't really care because I'm just using it to set innerHTML.

Thank you.

Answer

Eric Fortis picture Eric Fortis · Jan 6, 2011
input = 0.3;
output = input.toFixed(2);
//output: 0.30