Calculating rounded percentage in Shell Script without using "bc"

user2354302 picture user2354302 · Jun 18, 2014 · Viewed 43.8k times · Source

I'm trying to calculate percentage of certain items in Shell Script. I would like to round off the value, that is, if the result is 59.5, I should expect 60 and not 59.

item=30
total=70
percent=$((100*$item/$total))

echo $percent

This gives 42.

But actually, the result is 42.8 and I would to round it off to 43. "bc" does the trick, is there a way without using "bc" ?

I'm not authorized to install any new packages. "dc" and "bc" are not present in my system. It should be purely Shell, cannot use perl or python scripts either

Answer

Michael Back picture Michael Back · Jun 19, 2014

Use AWK (no bash-isms):

item=30
total=70
percent=$(awk "BEGIN { pc=100*${item}/${total}; i=int(pc); print (pc-i<0.5)?i:i+1 }")

echo $percent
43