March 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031

Categories

March 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031

Calculating percentages in bash

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

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>