How to convert numbers to string in JavaScript
We can convert a number to a string in 3 ways:
- Using the
toStringmethod - Using the
String()constructor - Concatenating the Number with an empty string
Using toString
We can use the toString method to convert numbers to String. Make sure the number is not undefined or null.
let a = 100;console.log("Converting 100 to string", a.toString());let floatingNum = 100.12200;console.log("Converting 100.12200 to string", floatingNum.toString());console.log("Converting NaN to string", NaN.toString());try{console.log("\n------\ncalling toString on null");(null).toString(); //error} catch(e) {console.log(e.message);}try{console.log("\n-----\ncalling toString on undefined");(undefined).toString(); //error} catch(e) {console.log(e.message);}
Using the String() constructor
We can use the String() constructor to convert a number to a string. When null or undefined is passed, then null and undefined Strings will be returned (respectively).
let num = 10;console.log("Conveting 10 to String =", String(num));let floatingNum = 20.12200;console.log("Conveting 20.12200 to String =", String(floatingNum));console.log("Conveting undefined to String =", String(undefined));console.log("Conveting null to String =", String(null));console.log("Conveting NaN to String =", String(NaN));
Concatenating the number with an empty string
By adding an empty string, the number will internally be converted to String.
let num = 10;console.log("Conveting 10 to String =", (num + '') );let floatingNum = 20.12200;console.log("Conveting 20.12200 to String =", (floatingNum + ''));console.log("Conveting undefined to String =", (undefined + ''));console.log("Conveting null to String =", (null + '') );console.log("Conveting NaN to String =", (NaN + ''));
In addition to the above methods, we can use template a literal to convert a number to String. Use ${num} to convert a number to String.
let num = 10;// `${}`console.log("Conveting 10 to String =", `${num}` );let floatingNum = 20.12200;console.log("Conveting 20.12200 to String =", `${floatingNum}`);console.log("Conveting undefined to String =", `${undefined}` );console.log("Conveting null to String =", `${null}` );console.log("Conveting NaN to String =", `${NaN}`);