Convert numbers to and from balanced ternary
The Balanced Ternary Converter translates ordinary decimal integers into balanced ternary — the elegant base-3 system whose digits are −1, 0 and +1 — and back again. Negative numbers are handled naturally, with no sign bit and no minus symbol, because the digit set is symmetric around zero.
How it works
To convert a positive integer to balanced ternary, repeatedly divide by 3 and inspect the remainder:
remainder 0 -> digit 0
remainder 1 -> digit 1
remainder 2 -> digit T (-1), and add 1 carry to the quotient
The carry on a remainder of 2 is the key trick: since 2 = 3 − 1, you write −1 in this position and bump the next position up by one. Reading the recorded digits from last to first gives the balanced ternary value. To convert back, evaluate the string left to right with total = total × 3 + digit, where T is −1.
Negation is free: swap every 1 with T and every T with 1. That is why the converter handles negative inputs by converting the absolute value and flipping the digits.
Worked examples
Decimal 5 → balanced ternary
5 ÷ 3 = 1 remainder 2 → digit T, carry 1 → quotient becomes 1+1 = 2
2 ÷ 3 = 0 remainder 2 → digit T, carry 1 → quotient becomes 0+1 = 1
1 ÷ 3 = 0 remainder 1 → digit 1
read digits last-to-first: 1 T T
check: 1×9 + (−1)×3 + (−1)×1 = 9 − 3 − 1 = 5 ✓
Decimal −5 → balanced ternary
Negate 1TT by swapping every 1 with T and every T with 1 → T11
Check: (−1)×9 + 1×3 + 1×1 = −9 + 3 + 1 = −5 ✓
Why balanced ternary is interesting
Most numeral systems handle negative numbers with a separate sign bit (binary) or a minus symbol. Balanced ternary encodes the sign implicitly: if the leading digit is 1 the number is positive; if it is T the number is negative. This means:
- Negation is trivially cheap — flip all digits, no subtraction circuit needed.
- Rounding is built in — truncating a balanced ternary fraction always rounds to the nearest value, not always downward as binary truncation does.
- Symmetric range — an n-trit balanced ternary number can represent the range
−(3^n − 1)/2to+(3^n − 1)/2, centred perfectly on zero.
These properties inspired the Soviet Setun (1958) and Setun 70 computers, the only balanced-ternary electronic computers ever built commercially. They also make balanced ternary the natural language for the classic balance-scale puzzle, where each weight can go on the left pan, the right pan, or stay off the scale — exactly three states per weight.
Reading the output
The converter displays the result using T for −1, 0 for zero, and 1 for positive one. To verify by hand, multiply each digit by 3 raised to its position (rightmost = position 0) and sum: 1TT is 1×9 + (−1)×3 + (−1)×1 = 5. Inputs are capped at JavaScript’s safe integer range so the repeated-division algorithm stays exact.