This is defined in the ECMAScript spec. However, the language of the spec is rigorous and not straightforward to read. Here’s a plain English explanation for the case in which radix = 10
(i.e., when you call x.toString()
with no additional parameter):
- If
x
isNaN
,x.toString()
returns"NaN"
. - Else if
x
is zero (+0
or-0
),x.toString()
returns"0"
. - Else if
x
is negative,x.toString()
returns the string concatenation of"-"
and(-x).toString()
. - Else if
x
isInfinity
,x.toString()
returns"Infinity"
. - Else if
x>=1e-6
andx<1e21
,x.toString()
returns the fixed-point notation ofx
. For example:(100).toString()
returns"100"
.100.11.toString()
returns"100.11"
.1e-6.toString()
returns"0.000001"
.
- Else (here,
x
must be positive and not in the range specified in 5),x.toString()
returns the scientific notation ofx
. For example:1e21.toString()
returns"1e+21"
.9.9999999999999e-7.toString()
returns"9.9999999999999e-7"
.