How to use the ‘toString()’ method in JavaScript In Javascript
The toString method takes the input as the decimal number and also the base value, converts this into the equivalent base, and prints using the log() function.
Example: In this example, we are performing decimal to any base conversion using the ‘toString’ method
function decToBase(inputNumber, inputBase) {
if (inputBase < 2 || inputBase > 36) {
return "Not Valid Base";
}
return inputNumber.toString(inputBase);
}
let inputNo = 1100;
let inputBase = 2;
let output = decToBase(inputNo, inputBase);
console.log(
`The Decimal ${inputNo} in base ${inputBase} is: ${output}`);
Output
The Decimal 1100 in base 2 is: 10001001100
JavaScript Program for Decimal to any base conversion
In this JavaScript article, we will see how we can do decimal to any base conversion in JavaScript. The base can not be less than 2 and can not exceed 36, So we always have to find out the base of a decimal that lies in between this range, which is ‘2=< base <=36’.
Example:
Input: number = "1100", base = 2
Output: 10001001100
There are different types of methods to perform decimal to any base conversion in JavaScript:
Table of Content
- Using the ‘toString()’ method in JavaScript
- Using the loop (do-while)
- Using the Array
- Using the Recursion
- Using Bitwise Operations
Contact Us