JavaScript toExponential() Method
This tutorial covers the toExponential() method of JavaScript's Number object. The toExponential() method returns a string representation of a number in exponential form (in the form "1.23e+4
").
The optional, numerical argument passed to toExponential() determines how many significant digits will be used. If no argument is passed, toExponential() will use all digits of the number on which is applied.
Using the toExponential() Method without Argument
When called without argument on a number, the toExponential() method will retain all significant digits of that number.
var numex = 123.456;
alert( numex.toExponential() ); // No argument passed
Our numerical variable contains six significant digits; all are retained by the toExponential() method, since no argument was passed:
Using the toExponential() Method with an Argument
Using the same script as earlier, we now pass 3 as argument to the toExponential() method.
var numex = 123.456;
alert( numex.toExponential(3) );
Since the argument we passed to toExponential() is smaller than the number of significant digits in the number on which it was applied, the resulting number has been rounded:
Notice that three digits (our argument) have been maintained after the decimal point of the exponential notation, but four digits have been retained overall. The script below passes an argument larger than the number of significant digits in our original number:
var numex = 123.456;
alert( numex.toExponential(8) );
As a result, the toExponential() method padded the resulting number with trailing zeroes:
Test the Number.toExponential() Method
Interactively test the Number.toExponential() method by editing the JavaScript code below and clicking the Test Number.toExponential() method button.
Browser support for JavaScript Number toExponential() method | |||
---|---|---|---|