W3cubDocs

/JavaScript

Number.prototype.toString()

The toString() method returns a string representing the specified Number object.

Try it

Syntax

toString()
toString(radix)

Parameters

radix Optional

An integer in the range 2 through 36 specifying the base to use for representing numeric values.

Return value

A string representing the specified Number object.

Exceptions

RangeError

If toString() is given a radix less than 2 or greater than 36, a RangeError is thrown.

Description

The Number object overrides the toString() method of the Object. For Number objects, the toString() method returns a string representation of the object in the specified radix.

The toString() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), a through f are used.

If the radix is not specified, the preferred radix is assumed to be 10.

If the numObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the numObj preceded by a - sign, not the two's complement of the numObj.

If the numObj is not a whole number, the 'dot' sign is used to separate the decimal places.

Examples

Using toString

const count = 10;

console.log(count.toString());    // displays '10'
console.log((17).toString());     // displays '17'
console.log((17.2).toString());   // displays '17.2'

const x = 6;

console.log(x.toString(2));       // displays '110'
console.log((254).toString(16));  // displays 'fe'

console.log((-10).toString(2));   // displays '-1010'
console.log((-0xff).toString(2)); // displays '-11111111'

Converting radix of number strings

If you have a string representing a number in a non-decimal radix, you can use parseInt() and toString() to convert it to a different radix.

const hex = "CAFEBABE";
const bin = parseInt(hex, 16).toString(2); // "11001010111111101011101010111110"

Beware of loss of precision: if the original number string is too large (larger than Number.MAX_SAFE_INTEGER, for example), you should use a BigInt instead. However, the BigInt constructor only has support for strings representing number literals (i.e. strings starting with 0b, 0o, 0x). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library.

Specifications

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
toString
1
12
1
3
4
1
4.4
18
4
10.1
1
1.0
1.0
0.10.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString