Fixed or floating-point arithmetic

If you try out a few of the preceding mathematical expressions, you might notice that some of the expanded values seem wrong:

$ printf '%.2f\n' "$((3/2))"
1.00

You may have expected a value such as 1.50 to be returned here, but Bash does not support floating-point or fixed-point arithmetic, only integer arithmetic. Fractional parts for these operations are lost.

If you need to perform arithmetic with non-integers using tools that are highly likely to be available on a POSIX system, your best bets are the bc calculator for fixed-point, or an AWK program for floating-point:

$ bc <<'EOF'
scale=2
3/2
EOF
1.50
$ awk 'BEGIN { printf "%.2f\n", 3/2 }'
1.50

If you have to do a lot of these sorts of operations, you ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.