JavaScript Number toString() method is “used to convert any number type value into its string type representation”.
To convert a number or integer to a string in JavaScript, you can use the “Number.toString()” method. For example, my_string = toString(my_int).
Syntax
number.toString(base)
Parameters
base: It is the base parameter that defines the base where the integer is represented in the string. Must be an integer between 2 and 36.
- Base 2 is binary.
- Base 8 is octal.
- Base 16 is hexadecimal.
Return Value
The number.toString() function returns a string representing the specified Number object.
Example
The toString() is a built-in method that accepts a radix argument, an optional argument, and converts a number to a string.
let a = 11;
let b = 11.00;
let c = 11.21;
let d = 19;
let opA = a.toString(2);
let opB = b.toString(2);
let opC = c.toString(2);
let opD = d.toString(2);
console.log(opA, typeof (opA));
console.log(opB, typeof (opB));
console.log(opC, typeof (opC));
console.log(opD, typeof (opD));
Output
1011 string
1011 string
1011.00110101110000101000111101011100001010001111011 string
10011 string
You can see that we converted int to string in the base of 2.
The num.toString() is fast and better than the + concatenation.
Converting a number to a string with base 8
To convert an integer to a string with base 8, use the toString() method by passing 8 as a parameter.
let a = 11;
let b = 11.00;
let c = 11.21;
let d = 19;
let opA = a.toString(8);
let opB = b.toString(8);
let opC = c.toString(8);
let opD = d.toString(8);
console.log(opA, typeof (opA));
console.log(opB, typeof (opB));
console.log(opC, typeof (opC));
console.log(opD, typeof (opD));
Output
13 string
13 string
13.1534121727024366 string
23 string
After changing the base, you can see that our output is different.
Converting a number to a string with base 16
To convert an integer to a string with base 16, use the toString() method by passing 16 as a parameter.
let a = 11;
let b = 11.00;
let c = 11.21;
let d = 19;
let opA = a.toString(16);
let opB = b.toString(16);
let opC = c.toString(16);
let opD = d.toString(16);
console.log(opA, typeof (opA));
console.log(opB, typeof (opB));
console.log(opC, typeof (opC));
console.log(opD, typeof (opD));
Output
b string
b string
b.35c28f5c28f6 string
13 string
That’s it.