破解到固定的实现 [英] broken toFixed implementation

查看:93
本文介绍了破解到固定的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javascript的Number.toFixed的默认实现似乎有点破碎。

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.

在8.500和8.660之间的范围内,以下数字不能正确地向上舍入。

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);
};


推荐答案

这是因为浮点错误。

(8.575).toFixed(20)(8.575)进行比较.toFixed(3) 并想象一下这个命题: 8.575< real(8.575),其中real是一个虚构函数,可以创建一个具有无限精度的实数。

Compare (8.575).toFixed(20) with (8.575).toFixed(3) and imagine this proposition: 8.575 < real("8.575"), where real is an imaginary function that creates a real number with infinite precision.

原始数字不符合预期并且已经引入了不准确性。

That is, the original number is not as expected and the inaccuracy has already been introduced.

我能想到的一个快速工作是:乘以1000(或(视情况而定),得到 toFixed(0)(仍然有一个限制,但这是荒谬的),然后以小数形式推回。

One quick "workabout" I can think of is: Multiply by 1000 (or as appropriate), get the toFixed(0) of that (still has a limit, but it's absurd), then shove back in the decimal form.

快乐编码。

这篇关于破解到固定的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆