Bash - Calculate Percentage [duplicate]

I am trying to calculate on a Linux System. I do have two different numbers, defined with a variable

$1= 1024$2= 20

My task is now to calculate how many percent are 20 of 1024. The calculation would be (100/1024*20) The problem is, that bash always says 0 with this type of code:

echo $((100/$1*$2))

Do anyone have an idea how i can calculate this?

4

3 Answers

you can do this using bc -l command. Eg. echo "100/1024*20" | bc -l gives 1.953125

1

Your attempt didn't work because you are performing integer calculation:

100/1024 = 0 // integer calculation
100/1024 = 0.09765625 // floating point calculation

So, you need to explain in some way that floating point calculation is to be done.
You can do it as follows:

awk 'BEGIN {print (100/1024*20)}'

More examples can be found in this post.

4

You can tell bc to show results in 2 (or desired number of) decimal places. Use below command

echo "scale=8; 100 / $1 * $2" | bc

On my computer, it reported something like below:

1.95312500

You can change the number of decimal places by passing correct numebr to 'scale' attribute.

2

You Might Also Like