Limit the amount of number shown after a decimal place in javascript

dotty picture dotty · Nov 23, 2010 · Viewed 48.7k times · Source

Hay, i have some floats like these

4.3455
2.768
3.67

and i want to display them like this

4.34
2.76
3.67

I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.

Answer

T.J. Crowder picture T.J. Crowder · Nov 23, 2010

You're looking for toFixed:

var x = 4.3455;
alert(x.toFixed(2)); // alerts 4.35 -- not what you wanted!

...but it looks like you want to truncate rather than rounding, so:

var x = 4.3455;
x = Math.floor(x * 100) / 100;
alert(x.toFixed(2)); // alerts 4.34