In this article, we will convert a number to a string in Javascript.
In JavaScript, you can change any number into string format using the following methods:
Table of Content
Method 1: Using toString() Method
This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type.
Syntax:
num.toString();
Example: This example uses the toString() method to convert a number into a string.
let a = 20; console.log(a.toString()); console.log((50).toString()); console.log((60).toString()); console.log((7).toString(2)); // (7 in base 2, or binary)
|
20 50 60 111
Method 2: Using the String() function
This method accepts an integer or floating-point number as a parameter and converts it into string type.
Syntax:
String(object);
Example: This example uses the String() function to convert a number into a string.
let a = 30; console.log(String(a)); console.log(String(52)); console.log(String(35.64)); |
30 52 35.64
Note: It does not do any base conversations as .toString() does.
Method 3: Concatenating an Empty String
This is arguably one of the easiest ways to convert any integer or floating-point number into a string.
Syntax:
let variable_name =' ' + value;
Example: In this example, we will concatenate a number into a string and it gets converted to a string.
let a = '' + 50;
console.log(a); |
50
Method 4: Using Template Strings
Injecting a number inside a String is also a valid way of parsing an Integer data type or Float data type.
Syntax:
let variable_name = '${value}';
Example: This example uses template strings to convert a number to a string.
let num = 50; let flt = 50.205; let string = `${num}`; let floatString = `${flt}`; console.log(string); console.log(floatString); |
50 50.205
Method 5: Using toLocaleString() Method
The toLocaleString() method converts a number into a string, using a local language format.
Example:
let number = 92; let numberString = number.toLocaleString(); console.log(numberString); |
92
Method 6: Using Lodash _.toString() Method
In this approach, we are using Lodash _.toString() method that convert the given value into the string only.
Example: This example shows the implementation of the above-explained approach.
// Requiring the lodash library const _ = require( "lodash" );
// Use of _.toString() method console.log(_.toString(-0)); |
Output:
'-0'