为什么console.log不显示分配的var的IEEE-754浮点值? [英] Why does console.log not show IEEE-754 floating point value of assigned var?

查看:81
本文介绍了为什么console.log不显示分配的var的IEEE-754浮点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JavaScript中的浮点值是以IEEE 754中指定的二进制base-2格式存储的.对我来说,这意味着当我将文字值.1分配给变量时,实际存储的值将是0.100000001490116119384765625(或诸如此类的高精度数字-我的数学可能是错误的).

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).

但是与该假设相反,存储值的console.log不能反映这一点.如下代码: var a = 0.1; console.log(a);

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);

...在Chrome和其他浏览器中执行时,将输出: 0.1

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

我希望它是: 0.100000001490116119384765625

I would have expected it to be: 0.100000001490116119384765625

此时a的值是否保持0.10.1000000...?如果是后者,那么console.log()通过什么方式显示0.1?我对这里引擎盖下发生的事情很感兴趣. (例如,JS是否在变量中存储数字的文本表示形式?)

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?"

推荐答案

JavaScript的浮点值默认格式仅使用了足够的十进制数字将该值与相邻的浮点值唯一区分开来.

这个问题是重复的,除了它使用console.log(它在JavaScript之外)之外. JavaScript标准 ECMAScript 2017语言规范未提及console.供应商将此功能作为扩展提供.因此,每个供应商都可以实现自己的行为.但是,将console.logNumber结合使用将很有可能会使用通常的ToString行为,从而导致在上面链接的答案中进行了转换解释.

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.

这篇关于为什么console.log不显示分配的var的IEEE-754浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆