Converting Numbers to Strings using toFixed()
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 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 Below are the actual conversion results in your browser: Similar rounding errors may occur for smaller numbers, too: |
Math.round
method
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, JavaScripter.net.