Numbers
JavaScript stores numbers as floating point values.
This can create issues when dealing with decimal numbers, since the internal representation of the number can become slightly imprecise. Consider the classic example below, where you would expect the output to be exactly 0.3
.
You may also encounter floating point imprecision when subtracting, multiplying, and dividing decimal numbers.
This is the expected behavior by any system that implements the IEEE 754 standard for representing numbers in floating point.
Converting numbers to strings
To convert a number to a string with a fixed number of decimal places, use toFixed
.
The toPrecision
function returns a string with the specified number of significant digits, and toExponential
returns a string
in exponential notation with the given decimal precision.
You can also use toString
to produce a string representation of the number. The first argument of toString
is the
base to output in (default is base 10).
Infinity
and NaN
JavaScript has special values to represent infinity (Infinity
) and "not a number" (NaN
).
A common situation where NaN
arises in TypeScript programs is during the conversion of a string
value to number
.