user2354302 user2354302 - 2 years ago 251
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.


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 Source

Use AWK (no bash-isms):

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

echo $percent
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download