How to format a float in javascript? How to format a float in javascript? javascript javascript

How to format a float in javascript?


There are functions to round numbers. For example:

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

will print 5.04.

EDIT:Fiddle


var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)


Be careful when using toFixed():

First, rounding the number is done using the binary representation of the number, which might lead to unexpected behaviour. For example

(0.595).toFixed(2) === '0.59'

instead of '0.6'.

Second, there's an IE bug with toFixed(). In IE (at least up to version 7, didn't check IE8), the following holds true:

(0.9).toFixed(0) === '0'

It might be a good idea to follow kkyy's suggestion or to use a custom toFixed() function, eg

function toFixed(value, precision) {    var power = Math.pow(10, precision || 0);    return String(Math.round(value * power) / power);}