gpt4 book ai didi

javascript - javascript 中的 toFixed 方法缺乏精度

转载 作者:行者123 更新时间:2023-12-03 07:14:02 25 4
gpt4 key购买 nike

我在 chrome(v60.0.3112.101) 控制台中对 Number.prototype.toFixed 方法做了一些测试,发现有些东西让我很困惑。

为什么 1.15.toFixed(1) 返回“1.1”而不是“1.2”?
为什么 1.05.toFixed(1) 返回“1.1”而不是“1.0”?
等等... test on the chrome console


我在 ECMAScript specification 做研究.

NOTE 1 toFixed returns a String containing this Number value represented in decimal fixed-point notation with fractionDigits digits after the decimal point. If fractionDigits is undefined, 0 is assumed.

我知道 fixed point notation 是什么.但是我无法解释上面的谜题。谁能给个明确的解释?


顺便说一句,我想细节算术下specification应该改进。以1.105为例,其相关运算如下:

Let n be an integer for which the exact mathematical value of n ÷ 10^f - x is as close to zero as possible. If there are two such n, pick the larger n.

根据pick the larger n,应该考虑111而不考虑110,这与实际情况相矛盾。

最佳答案

我会尽力澄清围绕该问题的要点。首先是定点符号:

I know what's the fixed point notation. But I can't explain it well.

定点表示法与浮点表示法相对。大多数情况下, float 表示法具有更好的精度。但它也更难理解和计算。

好吧,让我们回到定点表示法。这也是实数的算术符号。区别在于定点表示法中的数字由具有比例因子的整数表示。例如:

如果你想写 4.56 并且你有一个 1/1000 比例因子,你的数字将由 4560 表示。实际上,4560 * (1/1000) = 4.56

现在我们知道定点符号是如何工作的,我们可以更好地理解 toFixed(n) 函数的结果。例如,假设比例因子为 1/1000(这不是实际值,但这样更容易将结果可视化)。

1.15.toFixed(1)

会取小数点,然后用定点数表示数,所以它不关心'5'。你在内存中得到的数字是 1100。这就是为什么这个数字四舍五入到最接近的劣值。

现在,您可以在 toFixed 函数的 MDN Doc 上看到,您最多可以保留 20 位小数。根据这些信息,我们可以说比例因子是 1/10^20。

我希望这能回答您的问题。

关于javascript - javascript 中的 toFixed 方法缺乏精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com