How to format a float in javascript?

F40 picture F40 · Mar 19, 2009 · Viewed 465.9k times · Source

In JavaScript, when converting from a float to a string, how can I get just 2 digits after the decimal point? For example, 0.34 instead of 0.3445434.

Answer

Tim Büthe picture Tim Büthe · Mar 19, 2009

There are functions to round numbers. For example:

var x = 5.0364342423;
print(x.toFixed(2));

will print 5.04.

EDIT: Fiddle