JavaScript Number toString()

The syntax of the toString() method is:

num.toString(radix)

Here, num is a number.


Number toString() Parameters

The toString() method takes in:

  • radix (optional) - An integer between 2 to 36 specifying the base to use for representing numeric values such as 2 (binary), 8 (octal), 16 (hexadecimal).

Note: If argument is less than 2 or greater than 32, a RangeError is thrown


Return value from Number toString()

  • Returns a string representing the given Number object in the specified radix(10 by default).

Example: Using toString()

var num1 = 2512;
// base 10 string representation
str_num1 = num1.toString(); // '2512'
console.log(str_num1);

// base 16 string representation
str_num1 = num1.toString(16); // '9d0'
console.log(str_num1);

var num2 = -10;
// base 2 string representation
// positive binary repr with negative sign rather than 2's complement
str_num2 = num2.toString(2); // '-1010'
console.log(str_num2);

var num3 = -5.645;
str_num3 = num3.toString(); // '-5.645'
console.log(str_num3);

Output

2512
9d0
-1010
-5.645

Recommended Readings: