Home >>Javascript Programs >Convert a number into different base in JavaScript

Convert a number into different base in JavaScript

Convert a number into different base in JavaScript

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

Normally the users can convert numbers into different bases, from base 2 to base 36 in JavaScript. We all are familiar with four number systems, namely, decimal, binary, octal, hexadecimal. The users have an object inherited prototype method which is called toString().

In this article, the main focus is the radix. We can use the radix to define the base system of the number. The user can applied this method on the number and takes output as a string.

Generally, we all are concerned with the decimal number system and with toString, by default the base in 10 in the toString method or decimal system.

Basically you can use the Number() method which helps you to transforms string to number.

So, this article will help you a lot how to code to Convert a number into the different base in JavaScript.

Let's take an example:

<!DOCTYPE html>
<html>
<body>
<button onclick="btn_str()">click me</button>
<p id="basestr"></p>
<script>
function btn_str() {
  var str = 25;
  var a = str.toString();
  var b = str.toString(2);
  var c = str.toString(8);
  var d = str.toString(16);
  var e = a + "<br>" + b + "<br>" + c + "<br>" + d;
  document.getElementById("basestr").innerHTML=e;
}
</script>
</body>
</html>
Output:

 


Popular Tutorials