broken toFixed implementation

后端 未结 6 2202
陌清茗
陌清茗 2020-11-27 21:51

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((         


        
6条回答
  •  时光取名叫无心
    2020-11-27 22:16

    Thanks for the answer pst. My implementation almost worked, but didn't in some cases because of floating point errors.

    this line in my function is the culprit: Math.round(this * factor)

    (it's on the Number.prototype, so "this" is the number); 8.575 * 100 comes out to 857.4999999999999, which in turn rounds down. this is corrected by changing the line to read as follows: Math.round(Math.round(this * factor * 100) / 100)

    My entire workaround is now changed to:

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

提交回复
热议问题