In this article, we will learn how to convert number to string in javascript or jquery.
There are many ways to do the conversion data from number to string and we will see in this article. In another article, you can learn how to convert a string to a number in javascript or jquery.
There are some built-in methods in javascript by which we can perform conversion of number to a string and these methods only differ in performance and readability.
These methods are as follows:
.toString()
String()
.toString()
MethodThe .
toString()
method converts a number to a string. This method takes a single parameter(radix) which is optional.
Parameter name(optional): radix, an integer in the range 2 through 36 specifying the base to use for representing numeric values.
If an optional parameter is passed as a parameter to the .toString()
method, the number will be parsed and converted according to that base number. Here are some examples using the .
toString()
method with or without a parameter:
let x = 20;
var a = x.toString(); // it will return '20'
var b = 50 .toString(); // it will return '50'
var c = (60).toString(); // it will return '60'
var d = (15).toString(2); // it will return '1111' (15 in base 2, or binary)
var e = (15).toString(8); // it will return '17' (15 in base 8, or octal)
var f = (15).toString(16); // it will return 'f' (15 in base 16, or hexadecimal)
String()
MethodThis method also converts the number to a string but the main difference between String()
and .toString()
methods are that the String()
method does not do any base conversion like .toString()
method. Here are some examples using String()
method:
let x = 20;
var a = String(x); // it will return '20'
var b = String(50); // it will return '50'
var c = String(55.225); // it will return '55.225'
The simplest way for converting a number to a string by concatenating the empty string with the number. This is the fastest way of conversion from number to a string. Using this method performance increases and lack of readability. Here are some examples using this method:
let x = 20;
var a = '' + x; // it will return '20'
var b = 50 + ''; // it will return '50'
var c = '' + 55.225; // it will return '55.225'
var d = '' + 281e-26 // it will return '2.81e-24'
A template string was introduced in ES6.
let x = 20;
var a = `${x}`; // it will return '20'
var b = `${50}`; // it will return '50'
var c = `${55.225}`; // it will return '55.225'
var d = `${2.81e-26}`; // it will return '2.81e-26'
I hope this article will help you to understand how to convert number to string in javascript or jquery.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments