Thursday, 8 May 2008

Calculating percentages in bash

Dividing in bash will cause problems if the result is below zero. This is a problem when you’re trying to work out percentages. For example, if you simply want to divide 1 by 2 the result should be 0.5. However, bash returns the result 0:
user@computer:~> echo $(( 1 / 2 ))
0
To fix this problem use the program bc, “an arbitrary precision calculator language”. Using bc you can do the calculation to a specified number of decimal places:
user@computer:~> echo “scale=2; 1 / 2″ | bc
.50
You can use this to work out the percentage as follows:
user@computer:~> echo “scale=2; 1 / 2 * 100″ | bc
50.00
To chop off the decimal places use sed:
user@computer:~> echo “scale=2; 1 / 2 * 100″ |  bc  |  sed s/\\.[0-9]\\+//
50

No comments:

Post a Comment