The Number toString() method

By

Learn how the JavaScript Number toString() method returns a string representation of a number, and how the optional radix prints it in binary, octal, or hex.

~~~

The toString() method returns a string representation of a number. It accepts an optional argument, the radix, which is the base you want to use for the output:

new Number(10).toString() //'10'
new Number(10).toString(2) //'1010'
new Number(10).toString(8) //'12'
new Number(10).toString(16) //'a'

The radix can be any integer from 2 to 36. When you leave it out, JavaScript uses base 10, so you get the number back as a normal decimal string.

When would you use this?

The most common case is converting a number to binary, octal, or hexadecimal. Colors on the web are hex, so this is how you turn a number into a color component:

const value = 255
value.toString(16) //'ff'

Bases above 16 use letters after f. Base 36 uses every digit and every letter, which is handy for short random IDs:

const id = Math.floor(Math.random() * 1e9).toString(36)
console.log(id) //something like 'fk3l9z'

Calling it on a number literal

You’ll notice the examples above use new Number(10), which wraps the value in a Number object. You rarely need that. You can call toString() on a plain number too, but a number literal needs a little care:

const n = 255
n.toString(16) //'ff'

That works because n is a variable. If you try it directly on a literal, the parser reads the dot as the start of a decimal:

255.toString(16) //SyntaxError

The fix is to add a second dot or wrap the number in parentheses, so JavaScript knows the dot is a property access and not a decimal point:

255..toString(16) //'ff'
(255).toString(16) //'ff'

Both give you 'ff'. My advice is to store the number in a variable first, like the earlier example. It reads better and you never hit that error.

One more thing to keep in mind: the result is always a string, even when the radix is 10. If you need to do math on it afterward, convert it back with Number() or parseInt().

~~~

Related posts about js: