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

bc for Floating-Point Math

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"

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.