How to Convert Number to String in JavaScript

09/30/2021

Contents

In this article, you will learn how to convert number to string in JavaScript.

Converting number to string in JavaScript

In JavaScript, you can convert a number to a string using the toString() method or the String() constructor. Converting a number to a string is useful when you need to concatenate it with other strings or display it as text on a webpage.

Using the toString() Method

The toString() method is a built-in method in JavaScript that converts a number to a string. Here’s the syntax for using the toString() method:

number.toString([radix])

The number is the number that you want to convert to a string. The radix is an optional parameter that specifies the base of the number system to use for the conversion. The default value for radix is 10, which is the decimal number system.

Here’s an example of using the toString() method to convert a number to a string:

let number = 42;
let string = number.toString();
console.log(string); // "42"

In this example, we use the toString() method to convert the number 42 to a string. The resulting string is then assigned to the string variable and logged to the console.

Using the String() Constructor

You can also convert a number to a string using the String() constructor. Here’s the syntax for using the String() constructor:

String(number)

The number is the number that you want to convert to a string.

Here’s an example of using the String() constructor to convert a number to a string:

let number = 42;
let string = String(number);
console.log(string); // "42"

In this example, we use the String() constructor to convert the number 42 to a string. The resulting string is then assigned to the string variable and logged to the console.

Converting a number to a binary, octal, or hexadecimal string

If you want to convert a number to a binary, octal, or hexadecimal string, you can use the toString() method with a radix parameter. The radix parameter specifies the base of the number system to use for the conversion.

Here are examples of converting a number to a binary, octal, or hexadecimal string:

let number = 42;
let binary = number.toString(2);
console.log(binary); // "101010"

let octal = number.toString(8);
console.log(octal); // "52"

let hexadecimal = number.toString(16);
console.log(hexadecimal); // "2a"

In these examples, we use the toString() method with a radix parameter to convert the number 42 to binary, octal, and hexadecimal strings. The resulting strings are then assigned to the corresponding variables and logged to the console.