JavaScript(JS) number method - tostring
The toString()
method is a built-in method of the Number
object in JavaScript. It returns a string representation of the number in a specified radix (base).
Here's an example usage:
const num = 42; console.log(num.toString()); // "42" console.log(num.toString(2)); // "101010" console.log(num.toString(8)); // "52" console.log(num.toString(16)); // "2a"
In the above example, the toString()
method is called on the num
variable, which is assigned the value 42
. When called with no argument, the method returns the string "42"
, which is the decimal representation of the number.
When called with an argument, the toString()
method converts the number to the specified radix (base) and returns a string representation of the number in that base. In the example above, the method is called with radixes of 2 (binary), 8 (octal), and 16 (hexadecimal).
Note that the radix argument must be an integer between 2 and 36. If the radix is not in this range, toString()
will return NaN
.
const num = 42; console.log(num.toString(1)); // "NaN" console.log(num.toString(37)); // "NaN"