To get the string format of a number in JavaScript is very easy. Take a look!
Contents
Method #1: Number.prototype.toString()
The simplest method is to use the Number.prototype.toString()
method of a number.
const number = 123;
number.toString(); // '123'
Note that be careful when using the toString()
method with a literal number:
123.toString();
// Uncaught SyntaxError: identifier starts immediately after numeric literal
In this case, you have 3 workarounds:
(123).toString(); // use parentheses
123..toString(); // use double dots
123 .toString(); // use a whitespace character after the number
I personally like the former one because of its clarity.
Method #2: String()
Using the String()
function returns a string from an input number.
const number = 123;
new String(number); // '123'
Method #3: Template strings
You can use a feature called the template strings of ES6 to produce a string from a number.
const number = 123;
`${number}`; // '123'
Conclusion
The conversion methods that I mentioned above are very clear, right?
There are also some methods, such as number + ''
or '' + number
, but they make the code unclear so you should use one of above methods instead.