Convert a number to a string in JavaScript
Last Updated :
07 Dec, 2023
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:
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.
Javascript
let a = 20;
console.log(a.toString());
console.log((50).toString());
console.log((60).toString());
console.log((7).toString(2));
|
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.
Javascript
let a = 30;
console.log(String(a));
console.log(String(52));
console.log(String(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.
Javascript
let a = '' + 50;
console.log(a);
|
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.
Javascript
let num = 50;
let flt = 50.205;
let string = `${num}`;
let floatString = `${flt}`;
console.log(string);
console.log(floatString);
|
The toLocaleString() method converts a number into a string, using a local language format.
Example:
Javascript
let number = 92;
let numberString = number.toLocaleString();
console.log(numberString);
|
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.
Javascript
const _ = require( "lodash" );
console.log(_.toString(-0));
|
Output:
'-0'
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...