﻿ toExponential ﻿

Main Page

# toExponential

The
toFixed()
method returns a string representation of a number with a specified number of decimal
points. For example:
var oNumberObject = new Number(99);
Here, the
toFixed()
method is given an argument of
2
, which indicates how many decimal places
should be displayed. As a result, the method returns the string
“99.00”
, filling out the empty decimal
places with 0s. This method can be very useful for applications dealing with currency. The
toFixed()
method can represent numbers with 0 to 20 decimal places; other values may cause errors.
Another method related to formatting numbers is the
toExponential()
method, which returns a string
with the number formatted in e-notation. Just as with
toFixed()
,
toExponential()
accepts one argu-
ment, which is the number of decimal places to output. For example:
var oNumberObject = new Number(99);
This code outputs
“9.9e+1”
as the result, which you may remember from the earlier explanation, repre-
sents 9.9 x 10
1
. The question is, what if you don’t know the proper format to use for a number: fixed or
exponential? That’s where the
toPrecision()
method comes in.
The
toPrecision()
method returns either the fixed or exponential representation of a number, depend-
ing on which makes the most sense. This method takes one argument, which is the total number of digits
to use to represent the number (not including exponents). Example:
var oNumberObject = new Number(99);
In this example, the task is to represent the number
99
with a single digit, which results in
“1e+2”
, oth-
erwise known as 100. Yes,
toPrecision()
rounded the number to get as close as possible to the actual
value. Because you can’t represent 99 with any fewer than 2 digits, this rounding had to occur. If, how-
ever, you want to represent 99 using two digits, well, that’s easy:
var oNumberObject = new Number(99);
Of course the output is
“99”
, because that is the exact representation of the number. But what if you
specify more than the number of digits needed?
var oNumberObject = new Number(99);
In this case,
toPrecision(3)
is exactly equivalent to
toFixed(1)
, outputting
“99.0”
as the result.
The
toFixed(), toExponential()
, and
toPrecision()
methods round up or down to accu-
rately represent a number with the correct number of decimal places.
28
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 28

Free JavaScript Editor     Ajax Editor