JavaScript How to Convert Number to String Easily
In JavaScript, convert a number to a string by using
number.toString() or the String(number) function.Examples
Input123
Output"123"
Input0
Output"0"
Input-45.67
Output"-45.67"
How to Think About It
To convert a number to a string, think about changing the number into text form so it can be used where words are needed. You can do this by calling a method on the number or by using a function that turns any value into a string.
Algorithm
1
Get the number you want to convert.2
Use the number's toString() method or the String() function to convert it.3
Return or use the resulting string.Code
javascript
const num = 123; const str1 = num.toString(); const str2 = String(num); console.log(str1); console.log(str2);
Output
123
123
Dry Run
Let's trace converting the number 123 to a string using toString()
1
Start with number
num = 123
2
Call toString()
str1 = num.toString() -> "123"
3
Print result
console.log(str1) outputs "123"
| Step | Value |
|---|---|
| Initial number | 123 |
| After toString() | "123" |
| Output | "123" |
Why This Works
Step 1: Using toString() method
The toString() method converts the number into its text form.
Step 2: Using String() function
The String() function takes any value and returns its string version.
Alternative Approaches
Template literals
javascript
const num = 123; const str = `${num}`; console.log(str);
Easy and readable, but uses string interpolation which may be less obvious for beginners.
Concatenation with empty string
javascript
const num = 123; const str = num + ''; console.log(str);
Quick trick to convert number to string by adding an empty string, but less explicit.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion is a simple operation that takes constant time regardless of the number size.
Space Complexity
Only a new string is created, so space used is constant and minimal.
Which Approach is Fastest?
All methods like toString(), String(), template literals, and concatenation run in constant time with negligible differences.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toString() | O(1) | O(1) | Clear and explicit conversion |
| String() | O(1) | O(1) | Converts any value, not just numbers |
| Template literals | O(1) | O(1) | Readable and flexible string creation |
| Concatenation with '' | O(1) | O(1) | Quick shorthand but less explicit |
Use
number.toString() for clear and direct conversion from number to string.Trying to convert a number without calling a method or function, which leaves it as a number type.