gpt4 book ai didi

Javascript:数字的字符串表示

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:49 24 4
gpt4 key购买 nike

javascript如何将数字转换成字符串?我希望它能将数字四舍五入到一定的精度,但看起来情况并非如此。我做了以下测试:

> 0.1 + 0.2
0.30000000000000004
> (0.1 + 0.2).toFixed(20)
'0.30000000000000004441'
> 0.2
0.2
> (0.2).toFixed(20)
'0.20000000000000001110'

这是 Safari 6.1.1、Firefox 25.0.1 和 node.js 0.10.21 中的行为。

看起来 javascript 在 (0.1 + 0.2) 时显示小数点后的第 17 位,但在 0.2 时隐藏它(因此数字四舍五入为 0.2)。

在 javascript 中,数字到字符串的转换到底是如何工作的?

最佳答案

来自问题的作者:

我在 ECMA 脚本规范中找到了答案:http://www.ecma-international.org/ecma-262/5.1/#sec-9.8.1

打印数字时,javascript 调用 toString()。 toString() 的规范解释了 javascript 如何决定打印什么。下面这个注释

The least significant digit of s is not always uniquely determined by the requirements listed in step 5.

还有这里的那个:http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.5

The output of toFixed may be more precise than toString for some values because toString only prints enough significant digits to distinguish the number from adjacent number values.

解释 toString() 行为背后的基本思想。

关于Javascript:数字的字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21441756/

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