javascript number literal using exponent

扶醉桌前 提交于 2019-12-13 02:56:50

问题


console.log(2E-12); // returns 2E-12
console.log(2E12); // returns 2000000000000

Why does line one return 2E-12 and not the same as line two. Is this an illegal way of using the exponent?


回答1:


From the ECMAScript specification of toString applied to the Number type:

7. If 0 < n ≤ 21, return the String consisting of the most significant n digits of the decimal representation of s, followed by a decimal point ‘.’, followed by the remaining k−n digits of the decimal representation of s.

8. If −6 < n ≤ 0, return the String consisting of the character ‘0’, followed by a decimal point ‘.’, followed by −n occurrences of the character ‘0’, followed by the k digits of the decimal representation of s.

9. Otherwise, if k = 1, return the String consisting of the single digit of s, followed by lowercase character ‘e’, followed by a plus sign ‘+’ or minus sign ‘−’ according to whether n−1 is positive or negative, followed by the decimal representation of the integer abs(n−1) (with no leading zeroes).

n is effectively the exponent of the number. So this says that if the exponent is between -7 and 21 the number should be displayed normally, otherwise exponential notation should be used.




回答2:


The renderer is being clever. If you try console.log(2E-6), you'll see it does what you're expecting. console.log(2E-7) does not...at least in Chrome and the current version of IE. Someone decided exponential notation was more legible for long fractional values.

Additionally, note that the 2e-12 you're getting is a number, not a string.

> console.log(2e-12*2e5)
4e-7


来源:https://stackoverflow.com/questions/25374051/javascript-number-literal-using-exponent

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