Javascript:数字的字符串表示

mar*_*nev 5 javascript string-formatting floating-point-precision

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'
Run Code Online (Sandbox Code Playgroud)

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

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

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

mar*_*nev 3

来自问题的作者:

我在 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.
Run Code Online (Sandbox Code Playgroud)

以及这里的一个: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.
Run Code Online (Sandbox Code Playgroud)

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