bc for Floating-Point Math
Bash can only count whole numbers, like a kid who only knows apples and not half apples. bc is the friend who understands decimals, so you hand the sum to bc.
In this page:
Syntax
result=$(echo "expression" | bc -l)
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
$(( ))for decimals, which truncates to integers. - Forgetting
scale=, soecho "10/3" | bcprints3. - Forgetting to install
bc, which is not present on every minimal system.
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: