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

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
Robert
  • 10,126
  • 19
  • 78
  • 130

2 Answers2

3

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.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
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
S McCrohan
  • 6,663
  • 1
  • 30
  • 39