JavaScript’s built-in support for formatting numbers is limited, but includes support
for a fixed number of decimal digits, fixed precision, and exponential notation. Fur‐
thermore, there is support for displaying numbers in other bases, such as binary,
octal, and hexadecimal.
By necessity, all of JavaScript’s number formatting methods return a string, not a
number; only a string can preserve the desired formatting (it is easy to convert back
to a number if necessary, however). The upshot of this is that you should only format
numbers immediately before displaying them; while you are storing them or using
them in calculations, they should remain unformatted number types.
Fixed Decimals
If you want a fixed number of digits past the decimal point, you can use
Number.pro
totype.toFixed
:
const
x
=
19.51
;
x
.
toFixed
(
3
);
// "19.510"
x
.
toFixed
(
2
);
// "19.51"
x
.
toFixed
(
1
);
// "19.5"
x
.
toFixed
(
0
);
// "20"
Note that this is not truncation: the output is rounded to the number of specified dec‐
imal digits.
Exponential Notation
If you wish to display numbers in exponential notation, use
Number.prototype.toEx
ponential
:
const
x
=
3800.5
;
x
.
toExponential
(
4
);
// "3.8005e+4";
x
.
toExponential
(
3
);
// "3.801e+4";
x
.
toExponential
(
2
);
// "3.80e+4";
x
.
toExponential
(
1
);
// "3.8e+4";
x
.
toExponential
(
0
);
// "4e+4";
Like
Number.prototype.toFixed
, output is rounded, not truncated. The specified
precision is the number of digits past the decimal.
Fixed Precision
If what you care about is a fixed number of digits (regardless of where the decimal
place falls), you can use
Number.prototype.toPrecision
:
let
x
=
1000
;
x
.
toPrecision
(
5
);
// "1000.0"
x
.
toPrecision
(
4
);
// "1000"
x
.
toPrecision
(
3
);
// "1.00e+3"
230 | Chapter 16: Math