JavaScript How to Convert Decimal to Octal Number
number.toString(8) in JavaScript to convert a decimal number to its octal string representation, for example, (10).toString(8) returns '12'.Examples
How to Think About It
toString(8). This gives the octal form as a string.Algorithm
Code
const decimalNumber = 83; const octalString = decimalNumber.toString(8); console.log(octalString);
Dry Run
Let's trace converting decimal 83 to octal using toString(8).
Start with decimal number
decimalNumber = 83
Convert to octal string
octalString = 83..toString(8) => '123'
Print result
console.log(octalString) outputs '123'
| Decimal | Octal String |
|---|---|
| 83 | 123 |
Why This Works
Step 1: Using toString with base 8
The toString(8) method converts the decimal number into a string representing the number in base 8 (octal).
Step 2: Result is a string
The output is a string because octal numbers are usually represented as strings in programming.
Step 3: Works for any decimal number
This method works for any positive integer decimal number to convert it to octal.
Alternative Approaches
function decimalToOctal(num) { let octal = ''; while (num > 0) { octal = (num % 8) + octal; num = Math.floor(num / 8); } return octal || '0'; } console.log(decimalToOctal(83));
const decimalNumber = 83; const octalString = parseInt(decimalNumber, 10).toString(8); console.log(octalString);
Complexity: O(log n) time, O(log n) space
Time Complexity
Converting a number to a string in base 8 takes time proportional to the number of digits in octal, which is about log base 8 of the number.
Space Complexity
The space needed is proportional to the length of the octal string, also about log base 8 of the number.
Which Approach is Fastest?
Using toString(8) is the fastest and simplest built-in method compared to manual division.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toString(8) | O(log n) | O(log n) | Quick and simple conversion |
| Manual division | O(log n) | O(log n) | Learning how base conversion works |
| parseInt + toString | O(log n) | O(log n) | When input is string and needs parsing |
number.toString(8) for a quick and easy decimal to octal conversion in JavaScript.toString(8) and try to convert numbers directly without specifying the base.