为什么console.log只显示由0.1 + 0.2 = 0.30000000000000004产生的部分数字 [英] Why console.log shows only part of the number resulting from 0.1+0.2=0.30000000000000004
问题描述
还没有在stackoverlow上询问这个问题!我不是在问为什么0.1 + 0.2不等于0.3,我问的是非常不同的东西!请在将其标记为重复之前阅读该问题。
This question wasn't asked on stackoverlow yet! I'm not asking why 0.1+0.2 doesn't equal 0.3, I'm asking very different thing! Please read the question before marking it as a duplicate.
我写过这个函数,显示JavaScript如何存储浮点数64位:
I've written this function that shows how JavaScript stores float numbers in 64 bits:
function to64bitFloat(number) {
var f = new Float64Array(1);
f[0] = number;
var view = new Uint8Array(f.buffer);
var i, result = "";
for (i = view.length - 1; i >= 0; i--) {
var bits = view[i].toString(2);
if (bits.length < 8) {
bits = new Array(8 - bits.length).fill('0').join("") + bits;
}
result += bits;
}
return result;
}
现在我想查看 0.1的结果实际上存储了+0.2
,因为它显示在控制台 0.30000000000000004
中。所以我做了以下几点:
Now I want to check if the result of 0.1+0.2
is actually stored as it's shown in the console 0.30000000000000004
. So I do the following:
var r = 0.1+0.2;
to64bitFloat(r);
结果数字是:
0 01111111101 0011001100110011001100110011001100110011001100110100
现在,让我们将其转换为二进制:
Now, let's convert it to the binary:
计算指数:
01111111101 = 1021
1021 - 1023 = -2
一起搞定,
1.0011001100110011001100110011001100110011001100110100 x 2 ** -2 =
0.010011001100110011001100110011001100110011001100110100
现在,如果我们使用此转换器将结果数转换为十进制数,我们得到:
Now, if we convert the resulting number into decimal using this converter, we get:
0.3000000000000000444089209850062616169452667236328125
为什么控制台不显示整数,而不仅仅是更多的有效数字?
Why doesn't console show the whole number, instead of just it's more significand digits?
推荐答案
console.log 方法是非标准的。在Firefox中,您可以使用格式指定小数位数说明符
The console.log method is non-standard. In Firefox, you can specify the number of decimal with a format specifier
console.log('%.60f', 0.1 + 0.2)
给出
0.300000000000000044408920985006261616945266723632812500000000
与您的转换器给出的数字相同。
Which is the same number as the one given by your converter.
请注意,这在chrome中不起作用。
Note that, this doesn't work in chrome.
结论:
- Javascript编号以IEEE 754-2008双精度64位二进制格式存储。
- 数字的字符串表示形式在 ECMAScript标准。
- console.log方法取决于浏览器,Firefox实现允许指定n显示数字的任意小数位数。
这篇关于为什么console.log只显示由0.1 + 0.2 = 0.30000000000000004产生的部分数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!