Converting Numbers to Strings using toFixed()

JavaScript FAQ | JavaScript Numbers FAQ  

Question: When I convert numbers to strings, can I guarantee exactly n decimal places in the resultant string?

Answer: The simplest way of converting a number variable to string is to concatenate the variable with an empty string. However, this conversion does not guarantee the number of decimal places in the string. If you want exactly n decimal places in the conversion result, use the toFixed method, like this:

str = x.toFixed(n);
Here x is the number to be converted, the string str is the conversion result, and n specifies how many fractional decimal places must appear in the resultant string. The method can also be used without the parameter n - you can simply write: x.toFixed(), which is equivalent to x.toFixed(0). Consider these examples:

var x = 2.31;
var s  = x.toFixed()    // result: '2'
var s0 = x.toFixed(0)   // result: '2'
var s1 = x.toFixed(1)   // result: '2.3'
var s2 = x.toFixed(2)   // result: '2.31'
var s3 = x.toFixed(3)   // result: '2.310'
var s4 = x.toFixed(4)   // result: '2.3100'

The toFixed method might not always ensure the correct rounding of the conversion results. For example, (0.947).toFixed(0) may produce either '0' or '1', depending on the browser; thus, in Internet Explorer 8 and older versions, (0.947).toFixed(0) produces '0' while in IE9, Firefox or Google Chrome the same conversion produces '1'.

Below are the actual conversion results in your browser: Similar rounding errors may occur for smaller numbers, too:

For correct rounding in older browsers browsers such as IE8, you can use the Math.round method
or Math.round in combination with toFixed – e.g. the following will work across browsers:

x=0.947;    s0=(Math.round(x)).toFixed(0)           // '1'
x=0.0947;   s1=(Math.round(10*x)/10).toFixed(1)     // '0.1'
x=0.00947;  s2=(Math.round(100*x)/100).toFixed(2)   // '0.01'
x=0.000947; s3=(Math.round(1000*x)/1000).toFixed(3) // '0.001'

Copyright © 1999-2012,