Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

broken toFixed implementation [duplicate]

Tags:

People also ask

What does toFixed() do in JavaScript?

Description. toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

How to round to decimal places in JavaScript?

Use the Math. round() function to round the result of multiplying the number by 10 . The Math. round function will round the result to the nearest integer.

How to add decimal number in JavaScript?

To add two decimal numbers in JavaScript use the toFixed() function to convert it to a string with some decimal places shaved off, and then convert it back to a number.


The default implementation of javascript's "Number.toFixed" appears to be a bit broken.

console.log((8.555).toFixed(2));    // returns 8.56
console.log((8.565).toFixed(2));    // returns 8.57
console.log((8.575).toFixed(2));    // returns 8.57
console.log((8.585).toFixed(2));    // returns 8.59

I need a rounding method that is more consistent than that.

In the range between 8.500 and 8.660 the following numbers don't round up correctly.

8.575
8.635
8.645
8.655

I've tried to fix the prototype implementation as follows, but it's only half way there. Can anyone suggest any change that would make it work more consistently?

Number.prototype.toFixed = function(decimalPlaces) {
    var factor = Math.pow(10, decimalPlaces || 0);
    var v = (Math.round(this * factor) / factor).toString();
    if (v.indexOf('.') >= 0) {
        return v + factor.toString().substr(v.length - v.indexOf('.'));
    }
    return v + '.' + factor.toString().substr(1);
};