Skip to content
Advertisements

Number.toString()

Why Number.toString ?

The JavaScript toString () method is used to return a string that represents the specified number object.

Syntax:

number.toString(radix)

radix (optional): An integer in the range 2 through 36 specifying the base to use for representing numeric values.

  • 2 – The number will show as a binary value
  • 8 – The number will show as an octal value
  • 16 – The number will show as an hexadecimal value

JavaScript toString Examples

Example 1

A 2-based string: ToString (2) is used to convert a number to a 2-based number.

        let num1 = 255;
        console.log(num1.toString(2));

        let num2 = 15;
        console.log(num2.toString(2));

        let num3 = 60;
        console.log(num3.toString(2));

output:

11111111
1111
111100


Example 2

A string with 8 bases: ToString (8) is used to convert a number to a 8-based number.

        let num1 = 255;
        console.log(num1.toString(8));

        let num2 = 15;
        console.log(num2.toString(8));

        let num3 = 60;
        console.log(num3.toString(8));

output:

377
17
74


Example 3

        let num1 = 255;
        console.log(num1.toString(16));

        let num2 = 15;
        console.log(num2.toString(16));

        let num3 = 60;
        console.log(num3.toString(16));

output:

ff
f
3c


Example 4

A string with 16 bases: ToString (16) is used to convert a number to a 16-based number.

        let num = 25;
        let x1 = num.toString();
        let x2 = num.toString(2);
        let x3 = num.toString(8);
        let x4 = num.toString(16);

        console.log(x1)
        console.log(x2)
        console.log(x3)
        console.log(x4)

output:

25
11001
31
19


Browser Support

Chromeyes
Edgeyes
Firefox1
Internet Exploreryes
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes
Advertisements

1 Comment »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: