bc for Floating-Point Math
In this page:
bc for Floating-Point Math
Bash arithmetic only handles integers, so bc (basic calculator) is used when you need decimal precision. You typically pipe an expression string into it, like echo "10 / 3" | bc -l, where -l loads a math library with more precision. This is the standard workaround for floating-point calculations in shell scripts.
Note: Always use bc -l rather than plain bc when you need decimal results, not just truncated integers.
Example: bc for Floating-Point Math
#!/bin/bash
result=$(echo "10 / 3" | bc -l)
echo "10 / 3 = $result"
result=$(echo "scale=2; 22/7" | bc -l)
echo "22 / 7 (2 decimal places) = $result"
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: