JavaScript: Round to a number of decimal places, but strip extra zeros
Yes, there is a way. Use parseFloat()
.
parseFloat((1.005).toFixed(15)) //==> 1.005
parseFloat((1.000000000).toFixed(15)) //==> 1
See a live example here: http://jsfiddle.net/nayish/7JBJw/
>>> parseFloat(0.9999999.toFixed(4));
1
>>> parseFloat(0.0009999999.toFixed(4));
0.001
>>> parseFloat(0.0000009999999.toFixed(4));
0
As I understand, you want to remove the trailing zeros in the string that you obtained via toFixed()
. This is a pure string operation:
var x = 1.1230000;
var y = x.toFixed(15).replace(/0+$/, ""); // ==> 1.123
Number(n.toFixed(15)) or +(n.toFixed(15))
will convert the 15 place decimal string to a number, removing trailing zeroes.