This is a tutorial on how to convert a number into a string using JavaScript.
In certain cases, you may need to do this in order to use one of JavaScript’s string-related functions on a number variable.
For example, if you need to split the JS variable by a character.
Using the toString() method.
The preferred approach is to use JavaScript’s toString() method like so:
//An example float number var num = 212.23; //Use the toString() method to convert the number //into a string. var numAsString = num.toString();
In the code above, we converted a float value containing decimal places into a string variable. We did this by using the toString() method, which returns a string that represents the object.
In this case, the “object” in question is our float variable.
Converting a number into a string by using concatenation.
An alternative approach is to use concatenation:
//The number variable in question var anotherNumber = 1234; //Use concatenation anotherNumber = '' + anotherNumber;
In the JavaScript snippet above, we concatenated our integer number with an empty string. As a result, the number becomes a part of a new string.
Although this approach works, I would advise against using it.
In my opinion, it lacks clarity. This is because it is not immediately clear what the code is trying to achieve. As a result, it might confuse other developers and make your code less readable.
Unless you’re running into performance issues with the toString() method, I would avoid this approach.
Performance.
It is worth noting that you’re unlikely to come across such performance issues. In reality, it would take an ungodly number of conversions for this approach to be worth switching to.
To sum it up, any gains will be negligible, especially in modern browsers. Instead, use the toString() method.
Related: Convert a string into a number using JavaScript.