The Wayback Machine - https://web.archive.org/web/20240829113737/https://www.geeksforgeeks.org/convert-a-number-to-a-string-in-javascript/
Open In App

Convert a number to a string in JavaScript

Last Updated : 12 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
22.4%
24.1K

Converting numbers to strings in JavaScript is a common task that can be achieved using various methods. Understanding these methods is essential for data manipulation and presentation in web development. This guide will cover the different ways to convert numbers to strings in JavaScript, including using the toString(), String(), and template literals. Mastering these techniques ensures efficient and accurate data handling in your projects.

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)); // (7 in base 2, or binary)

Output
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.

JavaScript
let a = 30;

console.log(String(a));
console.log(String(52));
console.log(String(35.64));

Output
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.

JavaScript
let a = '' + 50;
console.log(a);

Output
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.

JavaScript
let num = 50;
let flt = 50.205;
let string = `${num}`;
let floatString = `${flt}`;
console.log(string);
console.log(floatString);

Output
50
50.205

Method 5: Using toLocaleString() Method

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); 

Output
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.

JavaScript
// Requiring the lodash library 
const _ = require("lodash");

// Use of _.toString() method 
console.log(_.toString(-0));

Output:

'-0'

Converting numbers to strings in JavaScript is straightforward with methods like toString(), String(), and template literals. Each method offers unique benefits depending on your specific use case. By mastering these techniques, you can enhance your JavaScript skills and ensure precise data manipulation in your web development projects. Start implementing these methods to improve your coding efficiency and accuracy.



Previous Article
Next Article

Similar Reads

Minimum number of given operations required to convert a string to another string
Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice versa. Examples: Input: S = "011", T = "101" Outpu
15 min read
Convert a String to Number in JavaScript
Converting strings to numbers in JavaScript is a fundamental operation, crucial for various tasks like handling user inputs or data processing. By converting strings to numeric values, JavaScript enables developers to perform mathematical operations and comparisons accurately, enhancing the versatility and functionality of their applications. Table
5 min read
How to convert long number into abbreviated string in JavaScript ?
We are given a long number and the task is to convert it to the abbreviated string(eg.. 1234 to 1.2k). Here 2 approaches are discussed with the help of JavaScript. Approaches to Convert Long Number to Abbreviated String:Table of Content Using JavaScript methodsUsing Custom functionUsing logarithmsUsing Intl.NumberFormatUsing RecursionUsing External
6 min read
How to convert a float number to the whole number in JavaScript ?
In this article, we will convert a float number to a whole number in JavaScript. Below are various methods to convert float numbers to whole numbers in JavaScript: Table of Content Math.floor (floating argument): Math.ceil (floating argument) Math.round (floating argument)Math.trunc (floating argument)parseInt (floating argument)double bitwise not
4 min read
Generate string by incrementing character of given string by number present at corresponding index of second string
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices. Examples: Input: S = "sun", N = "966"Output: bat Input: S = "apple", N = "12580"Output: brute Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to t
4 min read
Convert string X to an anagram of string Y with minimum replacements
Given two strings X and Y, we need to convert string X into an anagram of string Y with minimum replacements. If we have multiple ways of achieving the target, we go for the lexicographically smaller string where the length of each string [Tex]\in [1, 100000] [/Tex] Examples: Input : X = "CDBABC" Y = "ADCABD" Output : Anagram : ADBADC Number of cha
13 min read
Convert the string into palindrome string by changing only one character
Given a string str. Check if it is possible to convert the string into palindrome string by changing only one character.Examples: Input : str = "abccaa" Output : Yes We can change the second last character i.e. 'a' to 'b' to make it palindrome string Input : str = "abbcca" Output : No We can not convert the string into palindrome string by changing
5 min read
Minimum cuts required to convert a palindromic string to a different palindromic string
Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic" Output : 2 Explanation : ci | v | ic --> ic |
15+ min read
Replace '?' to convert given string to a binary string with maximum count of '0' and "10"
Given string str, consisting of three different types of characters '0', '1' and '?', the task is to convert the given string to a binary string by replacing the '?' characters with either '0' or '1' such that the count of 0s and 10 in the binary string is maximum. Examples: Input: str = 10?0?11Output: 1000011Explanation:Replacing str[2] = '0' and
4 min read
Minimum increments by 1 or K required to convert a string into another given string
Given two strings X and Y both consisting of N uppercase alphabets and an integer K, the task is to find the minimum count of cyclic increments of any character in the string X by 1 or K required to convert the string X into string Y. Cyclic Increments: Incrementing character 'Z' by 1 or K starts from the character 'A'. Examples: Input: X = "ABCT",
7 min read
How to convert a normal string to a uppercase string using filter in VueJS ?
Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js templ
2 min read
Minimum operations to convert String A to String B
Given two strings consisting of lowercase alphabets A and B, both of the same length. Each character of both the strings is either a lowercase letter or a question mark '?'. The task is to find the minimum number of operations required to convert A to B, in one operation you can choose an index i, if A[i] is a vowel convert it to a consonant, and i
12 min read
Minimizing Cost to Convert Binary String to Fair String
Given a binary string S of size N. You had been given the task of converting the given string into a Fair string. You can do the following operation any number of times : If the ith character in S is 0, replace it with 1 using cost C[i].If the ith character in S is 1, replace it with 0 using cost C[i].You have to determine the minimum cost used to
7 min read
Check If it is Possible to Convert Binary String into Unary String
Given a binary string S of length N. You can apply following operation on S any number of times. Choose two adjacent characters, such that both are 1's or 0's. Then invert them, Formally, if both are 0's then into 1's or vice-versa. Then your task is to output YES or NO, by checking that using given operations, Is it possible to convert S into eith
6 min read
Convert Hexadecimal value String to ASCII value String
Given the Hexadecimal value string as input, the task is to convert the given hexadecimal value string into its corresponding ASCII format string. Examples:  Input: 6765656b73Output: geeks Input: 6176656e67657273Output: avengers The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. Being a Base-16 system, there are 16 possi
6 min read
How to convert rgb() color string into an object in JavaScript ?
Given a color in the form of rgb( ) or rgba() and the task is to convert it into an object where the keys are the color names and values are the color values. Example:Input: rgb(242, 52, 110) Output: { red: 242, green: 52, blue: 110 } Input: rgba(255, 99, 71, 0.5) Output: { red: 255, green: 99, blue: 71, alpha: 0.5 } Approach: To achieve this we us
2 min read
JavaScript Convert bytes to human-readable string
Given the size of a file (in Bytes), the task is to convert it into human-readable form using JavaScript. Here are a few methods to discuss. Example 1: This example converts the file Size(in Bytes) into human-readable form. It shows the values in decimal and for less than 1024 Bytes, it remains in Bytes. C/C++ Code let size = function (bytes) { if
2 min read
Convert user input string into regular expression using JavaScript
In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object Regular expressions (RegExp) are patterns used to
2 min read
How to convert CSV string file to a 2D array of objects using JavaScript ?
A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript. Given a comma-separated values (CSV) string to a 2D array, using Javascript
4 min read
How to convert string of any base to an integer in JavaScript ?
Given a string containing an integer value and along with that user passes a base value. We need to convert that string of any base value to an integer in JavaScript. String Integer "1002" 1002 For performing the above-illustrated task, we would be using a method (or a function) provided by JavaScript called as parseInt(). This is a special method,
3 min read
Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript
When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc. In this article, we will learn to convert the array objects to CSV string data. Given array objects ( key: value ) to CSV string comma-separated val
3 min read
Convert a JavaScript Enum to a String
Enums in JavaScript are used to represent a fixed set of named values. In JavaScript, Enumerations or Enums are used to represent a fixed set of named values. However, Enums are not native to JavaScript, so they are usually implemented using objects or frozen arrays. In this article, we are going to explore various approaches to converting a JavaSc
2 min read
How to Convert a Date String to Timestamp in JavaScript ?
In this article, we are going to learn about the conversion of Date strings to Timestamps by using JavaScript. Converting date strings to timestamps means translating human-readable date representations into numeric values, indicating the time's position in milliseconds since January 1, 1970. Several methods can be used to Convert a Date String to
2 min read
How to convert seconds to time string format hh:mm:ss using JavaScript ?
Given a time in seconds, the task is to convert the time into a string format hh:mm:ss. There are two approaches to solving this problem Below is the approach to convert seconds to time string format hh:mm:ss using JavaScript Table of Content Passing the seconds to a date objectCalculating the hours, minutes, and seconds individuallyApproach 1: Pas
4 min read
How to Convert a String to Lowercase in JavaScript ?
To convert a string to lowercase in JavaScript, you can use the toLowerCase() method. This method does exactly what it sounds like – it transforms all the characters in a string to lowercase. Example: Here, toLowerCase() is applied to the myString variable, and the result is stored in the lowercaseString variable. After this operation, lowercaseStr
1 min read
How to Convert an Array to a String in JavaScript ?
In JavaScript, you can convert an array to a string using the join() method or by using the toString() method. Both methods provide different ways to concatenate the elements of an array into a single string. Using join() method: The join() method joins all elements of an array into a string, using a specified separator between each element. C/C++
1 min read
How to Convert a String to Uppercase in JavaScript ?
In JavaScript, you can convert a string to uppercase using the toUpperCase() method, which is available on string objects. This method returns a new string with all alphabetic characters converted to uppercase. Syntax:string.toUpperCase()string: The string that you want to convert to uppercase.Example: Here, the toUpperCase() method is called on th
1 min read
How to Convert String to JSON in JavaScript?
In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Using eval()Using Function ConstructorUsing JSON.par
2 min read
JavaScript Convert a string to boolean
To Convert a string to Boolean, we have multiple approaches. We are going to learn how to Convert a string to Boolean. Below are the approaches used to Convert a string to Boolean: Table of Content Approach 1: Using JavaScript == OperatorApproach 2: Using JavaScript === OperatorApproach 3: Using the Boolean() functionApproach 4: Using a regular exp
5 min read
Convert string into date using JavaScript
In this article, we will convert a string into a date using JavaScript. A string must follow the pattern so that it can be converted into a date. A string can be converted into a date in JavaScript through the following ways: Table of Content Using JavaScript Date() constructorUsing JavaScript toDateString() methodUsing Date.parse() methodUsing Int
3 min read