← Back to Bash Course | Chapter 4: Loops | Lesson 7 of 14

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.
Syntax
bash
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

bash
#!/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"
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
  1. Using $(( )) for decimals, which truncates to integers.
  2. Forgetting scale=, so echo "10/3" | bc prints 3.
  3. Forgetting to install bc, which is not present on every minimal system.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.