How to convert decimal to octal in JavaScript ?
Given a number and the task is to convert the number from decimal to octal. This can be done by using number.toString(8) method. It takes the parameter which is the base of the converted string. In this case, the base will be 8.
Syntax:
number.toString(8)
Parameters:
- number: It holds the number in a decimal format which needs to be converted.
Example:
Input: 34 24680 Output: a = 42 b = 60150 Input: 20 56789 Output: 24 156725
Example 1:
javascript
<!DOCTYPE html> <html> <body> <script> var a = 34; var b = 24680; document.write( "a = " + a.toString(8) + "<br>" ); document.write( "b = " + b.toString(8) + "<br>" ); </script> </body> </html> |
Output:
a = 42 b = 60150
Example 2:
javascript
<!DOCTYPE html> <html> <body> <script> dec_to_bho = function (n, base) { if (n < 0) { n = 0xFFFFFFFF + n + 1; } switch (base) { case 'O' : return parseInt(n, 10).toString(8); break ; case 'P' : return parseInt(n, 10).toString(8); break ; case 'Q' : return parseInt(n, 10).toString(8); break ; default : return ( "Wrong input" ); } } console.log(dec_to_bho(20, 'O' )); console.log(dec_to_bho(56789, 'P' )); console.log(dec_to_bho(321, 'Q' )); </script> </body> </html> |
Output:
24 156725 501
Example 3:
javascript
<!DOCTYPE html> <html> <body style= "text-align:center;" > <h1 style= "color:green;" > GeeksForGeeks </h1> <p id= "up" ></p> <button onclick= "myGFG()" > Convert to octal </button> <p id= "down" style= "color: green" ></p> <script> var GFG_Var = 134; var up = document.getElementById( "up" ); up.innerHTML = GFG_Var; var down = document.getElementById( "down" ); function myGFG() { var GFG_Var2 = GFG_Var.toString(8); down = document.getElementById( "down" ); down.innerHTML = "oct of " + GFG_Var + " is = " + GFG_Var2; } </script> </body> </html> |
Output:
- Before clicking the button:
- After clicking the button: