Skip to content
Related Articles
Open in App
Not now

Related Articles

Convert a number to a string in JavaScript

Improve Article
Save Article
Like Article
  • Last Updated : 05 Jan, 2023
Improve Article
Save Article
Like Article

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.

Using toString(): 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




<script>
    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)
</script>


Output:

20
50
60
111

Using 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




<script>
    let a = 30;
      
    console.log(String(a));
    console.log(String(52));
    console.log(String(35.64));
</script>


Output:

30
52
35.64

Note: It does not do any base conversations as .toString() does.

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




<script>
    let a = '' + 50;
    console.log(a);
</script>


Output:

50

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




<script>
    let num = 50;
    let flt = 50.205;
    let string = "${num}";
    let floatString = "${flt}";
    console.log(string);
    console.log(floatString);
</script>


Output:

50
50.205

The above 4 methods can be used to convert any integer or floating-point number into a string.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!