Javascript: formatting a rounded number to N decimals
I think that there is a more simple approach to all given here, and is the method Number.toFixed()
already implemented in JavaScript.
simply write:
var myNumber = 2;myNumber.toFixed(2); //returns "2.00"myNumber.toFixed(1); //returns "2.0"
etc...
I found a way. This is Christoph's code with a fix:
function toFixed(value, precision) { var precision = precision || 0, power = Math.pow(10, precision), absValue = Math.abs(Math.round(value * power)), result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power)); if (precision > 0) { var fraction = String(absValue % power), padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0'); result += '.' + padding + fraction; } return result;}
Read the details of repeating a character using an array constructor here if you are curious as to why I added the "+ 1".
That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.
You could just add zeroes after the number, something like:
var s = number.toString();if (s.indexOf('.') == -1) s += '.';while (s.length < s.indexOf('.') + 4) s += '0';
(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)