user2354302 user2354302 - 6 months ago 108
Bash Question

Calculating rounded percentage in Shell Script without using "bc"

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

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
Comments