Why does console.log not show IEEE-754 floating point value of assigned var?

左心房为你撑大大i 提交于 2019-12-13 02:48:08

问题


I know that floating point values in JavaScript are stored with a binary base-2 format specified in IEEE 754. To me, this means that when I assign the literal value .1 to a variable, the value actually stored will be 0.100000001490116119384765625 (or some high-precision number like that--my math may be wrong).

But counter to that assumption, the console.log of a stored value does not reflect this. The following code: var a = 0.1; console.log(a);

...when executed in Chrome, and probably other browsers, will output: 0.1

I would have expected it to be: 0.100000001490116119384765625

Does the value of a at this point hold 0.1 or 0.1000000...? If the latter, then by what means does console.log() show 0.1? I'm interested in what's going on under the hood here. (E.g. Is JS storing a text representation of the number in the variable?)

For you diligent admins that might be a little quick to "mark as duplicate", please note that I am asking the opposite of the more common question and variations "Why do I suddenly see these wacky high-precision numbers?"


回答1:


JavaScript’s default formatting of floating-point values uses just enough decimal digits to uniquely distinguish the value from neighboring floating-point values.

This question is a duplicate except it uses console.log, which is outside of JavaScript. The standard for JavaScript, the ECMAScript 2017 Language Specification does not mention console. This feature is provided by vendors as an extension. So each vendor may implement their own behavior. However, it is somewhat likely that using console.log with a Number will use the usual ToString behavior, resulting in the conversion explain in the answer linked above.




回答2:


You are right! Neverthless I never noticed that and can't explain it. Maybe some different does. I assume it's just not shown, because it would irritate many people and for most stuff it's not an issue.

var a = 0.1;
console.log(a.toPrecision(21))


来源:https://stackoverflow.com/questions/49711366/why-does-console-log-not-show-ieee-754-floating-point-value-of-assigned-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!