bc — Arbitrary-precision calculator for the shell — bc, math, calc across all 5 shells
Equivalents in every shell
echo "2 + 2" | bcPOSIX-mandated. Default precision is INTEGER-only — for floating-point use `-l` (loads the math library + sets `scale=20`): `echo "3 / 7" | bc -l` → `0.42857142857142857142`. `<<<` here-string syntax is shorter: `bc -l <<< "3/7"`.
echo "2 + 2" | bcSame external `bc` binary. Zsh also has a built-in arithmetic expansion (`$(( 2 + 2 ))` for integers, `(( float = 3.0 / 7 ))` with `setopt FORCE_FLOAT`) — for simple math, the builtin is faster.
echo "2 + 2" | bcSame external binary. Fish `math` builtin handles most floating-point needs without forking: `math "3 / 7"` → `0.428571`. Use `math --scale=20` for higher precision. `bc` is needed only for arbitrary precision beyond `math`'s ~17 significant digits.
2 + 2pwsh evaluates math expressions natively — `2 + 2` prints `4`. For arbitrary precision use `[bigint]::Parse("100000000000000000000") + 1`. The `[Math]::*` static methods (`[Math]::Sqrt`, `[Math]::Pow`) cover the common scientific-calculator surface. No `bc` install needed.
set /a "2 + 2"`set /a` is the cmd math built-in — INTEGER-only, 32-bit signed (`2147483647` max). For floating-point, shell out to pwsh: `powershell -Command "3 / 7.0"`. No native `bc`.
Worked examples
Compute pi to 30 decimal places
echo "scale=30; 4*a(1)" | bc -lmath --scale=30 "4 * atan(1)"[Math]::Round([Math]::PI, 15) # double has ~15-17 digitsCalculate a percentage with 2-decimal precision
echo "scale=2; 47*100/123" | bc -lmath --scale=2 "47 * 100 / 123"[Math]::Round(47*100/123, 2)powershell -Command "[Math]::Round(47*100/123, 2)"Sum a column of numbers from stdin
paste -sd+ numbers.txt | bcstring join + (cat numbers.txt) | bc(Get-Content numbers.txt | Measure-Object -Sum).SumGotchas
- Without `-l`, `bc` uses INTEGER arithmetic: `echo "3 / 7" | bc` → `0` (not `0.428...`). The `scale=N` variable controls precision but only applies to division/modulo — `-l` both sets `scale=20` AND loads `s(), c(), a(), l(), e()` (sin/cos/atan/ln/exp).
- Alpine / BusyBox does NOT ship `bc` by default — `apk add bc` is needed. Many minimal Docker images break on `bc` invocations silently (the pipe receives empty stdout, downstream parsers see `0` or empty). Test for presence: `command -v bc >/dev/null || { echo "bc missing"; exit 1; }`.
- pwsh `2 + 2` works at the REPL but in a script context the bare expression may be discarded — wrap in `Write-Output (2 + 2)` or assign `$r = 2 + 2; $r`. Inline math inside string interpolation needs `$()`: `"$(2+2)"` not `"2+2"`.
- cmd `set /a "1024 * 1024 * 1024 * 8"` silently OVERFLOWS to a negative number (32-bit signed wrap) — there's no warning. For big-integer math always shell out to pwsh `[bigint]` or to bash `bc`.
- bc `^` is exponentiation only for INTEGER exponents (`2^10` works, `2^0.5` errors). For sqrt: `sqrt(2)` (built-in). For `pow(2, 0.5)` use `e(0.5 * l(2))` (exp of log) — the math is awkward by design.