Convert a number into different base in JavaScript

In this article, we will learn how to convert a number into different base in JavaScript?
Submitted by Abhishek Pathak, on October 21, 2017

The base or radix of a number is the number of unique digits, including zero, used to represent numbers in a positional numeral system. In the decimal number system, we use digits 0-9 to form the numbers. The binary number system is denoted by just two digits 0 and 1. In this article we will look at method to convert the base system of a number.

In JavaScript, we can convert numbers into different bases, from base 2 to base 36. We are familiar with four number systems, namely, binary, octal, decimal, hexadecimal. We have a object inherited prototype method called toString() which does the work for us.

The toString() method expects only a single parameter which is optional but the game changer and main focus of this article, the radix. A radix defines the base system of the number. This method is applied on the number and we get output as a string.

By default the base in the toString method is 10 or decimal system which is good, as mostly we are concerned with decimal number system and with toString, we get the output in the string, which can be used further for other string manipulations.

Code

var number = 20;
number.toString(); //Default
//Output: 20

number.toString(2); //Binary
//Output: 10100

number.toString(8); //Octal
//Output: 24

number.toString(16); //Hexadecimal
//Output: 14

These were the number systems that we are familiar with. Also note, we can convert this string to number using the explicit type conversion, using Number() method which transforms string to number. We can also use some other base system like,

Code

number.toString(5);
//Output: 40

JavaScript is awesome. Hope you like this article. Share your thoughts in the comments below.

JavaScript Examples »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.