JavaScript Reference ยท Number and BigInt
Number.prototype.toString() method
Reference for Number.prototype.toString(): convert a number to text, write it in binary, octal or hex with a radix from 2 to 36, and avoid common mistakes.
toString() turns a number into a string. Without arguments it gives the normal decimal text you see when you print a number. With a radix argument it writes the number in another base: 2 for binary, 8 for octal, 16 for hexadecimal, up to 36.
It is the standard way to build hex colors, binary views of flags, and compact identifiers from integers. The number itself is never changed.
(255).toString(); // "255" (255).toString(16); // "ff" (5).toString(2); // "101"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
numberValue.toString() numberValue.toString(radix)
| Name | Description |
|---|---|
radix |
Optional integer from 2 to 36. The base to write the number in. If omitted (or undefined), the base is 10. |
Return value: a string. Digits above 9 use lowercase letters a to z. A negative number keeps a leading -, and fractions are written with a ..
Exceptions: a RangeError if radix is outside 2 to 36. A TypeError if the method is called on a value that is not a number.
Usage notes
- Decimal output follows the same rules as
String(number). Very large or very small numbers switch to exponent form, such as"1e+21"or"1e-7". - Only integers give a neat result in other bases. A fractional value like
0.1has a long or repeating binary expansion, so the text can be long and still not exact. - Negative numbers are not two's complement.
(-5).toString(2)is"-101". To see the 32-bit pattern, shift first:(-5 >>> 0).toString(2). - Parsing back: use
parseInt(text, radix)for integers.Number("0xff")also works for0x,0band0oprefixes, but not for plain text like"ff". - Literals:
5.toString()is a syntax error. Write(5).toString(),5..toString()or use a variable. - Template literals and concatenation call the same conversion, so
`${n}`and"" + nmatchn.toString()for numbers. - BigInt has its own
toString(radix)with the same idea, and it stays exact for huge values.
Browser support
toString() with a radix is available in every browser and JavaScript runtime.
Related
Number(),toFixed(),toLocaleString(),parseInt(),BigInt- Lessons: Numbers, Type conversion