Description
The JavaScript Number method toString()
returns the string representation of a number.
Syntax
The method toString()
has the below syntax, where num
is a number.
num.toString(radix)
Parameters
The method toString()
allows the below parameters.
radix
(optional)
- It is an integer between 2 to 32.
- It specifies the base value to be used for representing a number, like 2 (for binary), 8 (for octal), 16 (for hexadecimal), and so on.
- If this value is not between 2 and 32, the method returns a
RangeError
. - The default value is 10 for decimal values.
Result
Returns a new string from the given number, without changing the original number.
Example 1: Using the Method
The below example shows the basic usage of the method.
var num = 1234;
// Using default base 10
document.write(num.toString()); // Prints: 1234
// Using base 2
document.write(num.toString()); // Prints: 10011010010
// Using base 8
document.write(num.toString()); // Prints: 2322
// Using base 16
document.write(num.toString()); // Prints: 4d2
Output:
1234
10011010010
2322
4d2
Example 2: Method Returning RangeError
The method returns a RangeError
for the parameter value not between 2 and 32.
var num = 1234;
// Returns RangeError
document.write(num.toString(0)); // Returns RangeError
document.write(num.toString(1)); // Returns RangeError
document.write(num.toString(33)); // Returns RangeError
document.write(num.toString(Infinity)); // Returns RangeError
document.write(num.toString(NaN)); // Returns RangeError
Output:
RangeError: toString() radix argument must be between 2 and 36
Overall
The JavaScript Number method toString()
returns the string representation of a number.