Converting numbers to base-7 representation in JavaScript

In JavaScript, converting a number to base-7 representation involves repeatedly dividing by 7, similar to binary conversion but using 7 instead of 2. Base-7 uses digits 0-6.

Understanding Base-7 Conversion

To convert a decimal number to base-7, we divide the number by 7 repeatedly and collect the remainders. The remainders, read in reverse order, form the base-7 representation.

Example

Here's how to implement base-7 conversion in JavaScript:

const base7 = (num = 0) => {
    let sign = num < 0 ? '-' : '';
    num = Math.abs(num);
    
    if (num === 0) return "0";
    
    let result = '';
    while (num > 0) {
        result = (num % 7) + result;
        num = Math.floor(num / 7);
    }
    return sign + result;
};

// Test with different numbers
console.log(base7(100));  // 202
console.log(base7(49));   // 100
console.log(base7(7));    // 10
console.log(base7(-25));  // -34
console.log(base7(0));    // 0
202
100
10
-34
0

How It Works

The algorithm works by:

  • Handling the sign separately for negative numbers
  • Repeatedly dividing by 7 and collecting remainders
  • Building the result string from right to left
  • Using Math.floor() for proper integer division

Step-by-Step Example for 100

Converting 100 to base-7:

// Step by step conversion of 100 to base-7
let num = 100;
let steps = [];

while (num > 0) {
    let remainder = num % 7;
    steps.push(`${num} ÷ 7 = ${Math.floor(num / 7)} remainder ${remainder}`);
    num = Math.floor(num / 7);
}

steps.forEach(step => console.log(step));
console.log("\nReading remainders from bottom to top: 202");
100 ÷ 7 = 14 remainder 2
14 ÷ 7 = 2 remainder 0
2 ÷ 7 = 0 remainder 2

Reading remainders from bottom to top: 202

Alternative Implementation

Using JavaScript's built-in toString() method:

const base7Simple = (num) => {
    return num.toString(7);
};

console.log(base7Simple(100));  // 202
console.log(base7Simple(49));   // 100
console.log(base7Simple(-25));  // -34
202
100
-34

Conclusion

Converting numbers to base-7 can be done manually using division and remainders or simply using JavaScript's toString(7) method. Both approaches handle positive and negative numbers correctly.

Updated on: 2026-03-15T23:19:00+05:30

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements