Rounding floats to ints with bc in bash

Alec Jacobson

August 16, 2009

weblog/

I've seen a lot of bizarre attempts to round floating point numbers to integers in bash. Here's my cheap hack using bc:
echo "($float+0.5)/1" | bc 
If your floating point number is in a variable called float then this will round up or down accordingly. As in 1.0 and 1.4 round to 1, while 1.5 and 1.9 round to 2.