To convert any number to exponential form, you can use the toExponential()
Number method in JavaScript.
Consider this number,
// number
const num = 45678;
Let's convert this to exponential form using the toExponential()
method like this,
// number
const num = 45678;
// convert to exponential form
const expNum = num.toExponential();
console.log(expNum); // "4.5678e+4"
The method also accepts an optional argument to specify the number of digits to show after the decimal point. Suppose if we want only 2
digits to show after the decimal point, we can pass that 2
as an argument to the method like this,
// number
const num = 45678;
// convert to exponential form
// pass 2 to show 2 digits after
// decimal point
const expNum = num.toExponential(2);
console.log(expNum); // "4.57e+4"
Now the output looks like this: 4.57e+4
.
See this example live in JSBin.
- ✅ One important thing to note here is that the
toExponential()
number method returns the value as astring
type and not as anumber
type.