Skip to content

JavaScript Convert Decimal to Octal

Ramesh Fadatare edited this page Aug 11, 2020 · 1 revision

In this example, we will write a JavaScript function to convert Decimal number to Octal number.

JavaScript Convert Decimal to Octal

function decimalToOctal (num) {
  var oct = 0; var c = 0
  while (num > 0) {
    var r = num % 8
    oct = oct + (r * Math.pow(10, c++))
    num = Math.floor(num / 8) // basically /= 8 without remainder if any
  }
  console.log('The decimal in octal is ' + oct)
}

decimalToOctal(2)
decimalToOctal(8)
decimalToOctal(65)
decimalToOctal(216)
decimalToOctal(512)

Output:

The decimal in octal is 2
The decimal in octal is 10
The decimal in octal is 101
The decimal in octal is 330
The decimal in octal is 1000
Clone this wiki locally