Number.prototype.toString()

Converts a number into a string, also in a different numeral system, e.g. binary or hexadecimal.

Returns
A string with the number written in the chosen numeral system.
On this page

Example

#
JavaScript
const points = 255

console.log(points.toString())
console.log(points.toString(2))
console.log(points.toString(16))
console.log(typeof points.toString())
Console
255
11111111
ff
string

Definition and usage

#

The toString() method returns the number written as text. Without an argument it uses the decimal system, so (42).toString() gives "42". String(42) and concatenating the number with a string give the same result, so in everyday code this method is mostly called with an argument.

The radix argument is the base of the numeral system, from 2 to 36. toString(2) shows the binary form, toString(16) the hexadecimal form, used among other things in CSS colors, and toString(36) uses digits plus every letter of the Latin alphabet, which gives short identifiers. The reverse conversion, from string to number, is done by Number.parseInt(text, radix).

When calling the method directly on an integer written as digits, wrap it in parentheses: (255).toString(16). Writing 255.toString(16) is a syntax error, because the period after the digits is treated as the start of a decimal part. On variables, parentheses aren’t needed.

Syntax

#
Syntax
number.toString()
number.toString(radix)

Parameters

#
  • radix

    number 2-36, optional

    The base of the numeral system. Defaults to 10.

More examples

#
RGB color in hexadecimal notation
JavaScript
function toHex(r, g, b) {
  return '#' + [r, g, b].map((part) => part.toString(16).padStart(2, '0')).join('')
}

console.log(toHex(250, 204, 21))
console.log(toHex(0, 128, 255))
Console
#facc15
#0080ff

Without padStart(2, "0"), a zero would turn into a single "0" and the color would end up with too few digits.

Converting both ways with parseInt()
JavaScript
const binary = (10).toString(2)

console.log(binary)
console.log(Number.parseInt(binary, 2))
console.log((123456789).toString(36))
console.log(Number.parseInt('21i3v9', 36))
Console
1010
10
21i3v9
123456789

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For displaying numbers to users, toLocaleString() and toFixed() are better. toString() doesn’t add thousands separators or fix the number of decimal places.
  • On an integer written as digits, write (10).toString(2). Without the parentheses you get a syntax error.
  • When converting to hexadecimal, pad the result with zeros using padStart(2, "0"), otherwise 5 turns into "5" instead of "05".

Related entries

#

Spotted a mistake or missing an example? Write to us.