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

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions