Convert an integer to a string in JavaScript
This post will discuss how to convert an integer to a string in JavaScript.
There are several ways to convert an integer to a string in JavaScript. Here are some of the most common functions:
1. Using toString() function
One way is to use the toString() function, which is a built-in function of the number object. This function converts a number to a string and returns the result. We can use this function to convert an integer to a string by calling it on the integer value. For example, we can convert an integer to a string using toString() like this:
|
1 2 3 4 5 |
var num = 100; var str = num.toString(); console.log(str); // str is "100" |
We can also use the toString() function for converting numbers to different bases, such as binary, octal, or hexadecimal. This function takes an optional argument called radix, which specifies the base to use for representing numeric values. The radix can be an integer between 2 and 36. The default value is 10, which means decimal.
2. Using String() function
Another way is to use the String() function, which converts any value to a string. This function will return a string value if the value can be converted to a string, and an empty string otherwise. We can use this function to convert an integer to a string by passing it as an argument. For example, using the same integer as before, we can convert it to a string using String() like this:
|
1 2 3 4 5 |
var num = 100; var str = String(num); console.log(str); // str is "100" |
3. Using concatenation operator
A third way is to use the (+) operator, which is a basic arithmetic operator that can also be used for string concatenation. This operator takes two values and returns a new value that is the result of adding them together. If one or both of the values are strings, it will return a string that is the concatenation of the values. We can use this operator to convert an integer to a string by adding an empty string ("") to it. For example:
|
1 2 3 4 5 |
var num = 100; var str = "" + num; console.log(str); // str is "100" |
4. Using template literals
Template literals are strings that allow embedded expressions and multi-line strings. We can use template literals to convert an integer to a string by enclosing the integer in backticks (` `) and using the ${ } syntax to insert it as an expression. For example, to convert the integer 100 to a string:
|
1 2 3 4 5 |
var num = 100; var str = `${num}`; console.log(str); // str is "100" |
That’s all about converting an integer to a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)