How to convert decimal to octal in JavaScript ?

In this article, we are 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)
The below examples show the conversion from decimal to octal.
Example 1: In this example, we will convert 34 and 24680 into octal numbers.
javascript
| <script>     vara = 34;     varb = 24680;          console.log("a = "+ a.toString(8));     console.log("b = "+ b.toString(8));         </script> | 
Output:
a = 42 b = 60150
Example 2: In this example, we will convert some numbers into octal numbers.
javascript
| <script>     dec_to_bho = function(n, base) {         if(n < 0) {             n = 0xFFFFFFFF + n + 1;         }         switch(base) {             case'O':                 returnparseInt(n, 10).toString(8);                 break;             case'P':                 returnparseInt(n, 10).toString(8);                 break;             case'Q':                 returnparseInt(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> | 
Output:
24 156725 501
Example 3: In this example, we will apply onclick function to convert some numbers into octal numbers.
javascript
| <body style="text-align:center;">     <h1 style="color:green;">         GeeksForGeeks     </h1>     <h3>         Convert to octal     </h3>      <p id="up"></p>       <button onclick="myGFG()">         Convert to octal     </button>      <p id="down"style="color: green"></p>       <script>         varGFG_Var = 134;         varup = document.getElementById("up");         up.innerHTML = GFG_Var;         vardown = document.getElementById("down");                  functionmyGFG() {             varGFG_Var2 = GFG_Var.toString(8);             down = document.getElementById("down");             down.innerHTML = "oct of "+ GFG_Var                 + " is = "+ GFG_Var2;         }      </script> </body> | 
Output:
 
Convert decimal to octal
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
 
				 
					


