Open In App

How to convert decimal to octal in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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>
    var a = 34;
    var b = 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':
                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>


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


Output:

Convert decimal to octal

Convert decimal to octal



Last Updated : 12 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads