Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 509
user2354302 Avatar asked Jun 18 '14 11:06

user2354302


1 Answers

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
like image 199
Michael Back Avatar answered Oct 14 '22 14:10

Michael Back