The Number toExponential() method
By Flavio Copes
Learn how the JavaScript Number toExponential() method returns a string with the number in exponential notation, and how to set the fractional part digits.
The toExponential() method returns a string representing the number in exponential notation.
Exponential notation writes a number as a value between 1 and 10, multiplied by a power of 10. It’s how scientists and calculators write very large or very small numbers without endless zeros. 123456 becomes 1.23456e+5, which reads as 1.23456 × 10⁵.
You can use this method to get a string representing the number in exponential notation:
new Number(10).toExponential() //1e+1 (= 1 * 10^1)
new Number(21.2).toExponential() //2.12e+1 (= 2.12 * 10^1)
You can also call it directly on a number value, as long as you wrap it in parentheses so the dot isn’t mistaken for a decimal point:
(123456).toExponential() //1.23456e+5
(0.00012).toExponential() //1.2e-4
Notice the negative exponent in the second example. Small numbers shift the decimal point the other way: 1.2e-4 means 1.2 × 10⁻⁴.
Setting the number of digits
You can pass an argument to specify the fractional part digits:
new Number(21.2).toExponential(1) //2.1e+1
new Number(21.2).toExponential(5) //2.12000e+1
Notice how we lost precision in the first example.
The number is rounded, not truncated:
(21.27).toExponential(1) //2.1e+1
(99.5).toExponential(1) //1.0e+2
In the second case, rounding 99.5 up gives 100, so the exponent bumps from 1 to 2.
The argument must be between 0 and 100. Anything outside that range throws a RangeError.
When would you use it?
Reach for it when displaying measurements that span many orders of magnitude, like scientific data or file sizes in a log. Writing 1.2e-4 is easier to scan than 0.00012 once the zeros pile up.
Its sibling methods cover the other formatting needs: toFixed() gives you a plain decimal with a set number of digits, and toPrecision() sets the total significant digits, switching to exponential form on its own when needed.
One pitfall
toExponential() returns a string, not a number:
typeof (10).toExponential() //'string'
If you use + on the result, JavaScript concatenates strings instead of adding numbers. Format the number only at the very end, when you’re ready to show it, and keep the original value around for calculations.
Related posts about js: