1

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?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
bigMre
  • 29
  • 1
  • 1
  • 8
  • Not clear, please post more realistic sample of input and output in your post and let us know then. – RavinderSingh13 Mar 21 '19 at 09:56
  • I think it's better to use `bc -l` for calculations here – dimcha Mar 21 '19 at 09:59
  • @Inian better duplicate: https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash – kvantour Mar 21 '19 at 14:29
  • This "kind" of code does not always return 0. Consider: `$((100* $2/$1))` . It is the same kind of code and gives the correct percentage truncated toward 0. It is also possible to get the result rounded to the nearest integer with the same kind of code, no bc or awk, etc. see https://stackoverflow.com/a/59414940/12559612. – Dominic108 Jan 02 '20 at 01:55

3 Answers3

4

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

mdeora
  • 4,152
  • 2
  • 19
  • 29
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.

Dominique
  • 16,450
  • 15
  • 56
  • 112
0

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.

Prasanna
  • 1,184
  • 8
  • 12
  • 1
    Please don't just say how to do it, but also explain why the original attempt does not work. – kvantour Mar 21 '19 at 10:16
  • 2
    That's already mentioned in answer by @dominique. And the OP did not ask 'why the original attempt does not work'. OP asked 'Do anyone have an idea how i can calculate this?', which I think I answered. – Prasanna Mar 22 '19 at 11:06