simple arithmetic in bash
I am trying to do a relatively easy arithmetic operation and bash is making it literally impossible. I have been searching google and tutorials for nearly 3 hours and about ready to just give up and say f*ck it.
This is what I'm trying to do: $x=309 $y=98 I am trying to perform "( y / x ) * 100" to get the percentage as a decimal. (the answer should be 31.71%) I have tried a thousand different combinations of things and have come up with nothing. I would like to murder the person who made the arithmetic so hard to perform in bash. I would be permanently in debt to whoever can help me out. Thanks, |
The nearest you will get with bash arithmatic is:
Code:
x=309 If you want to play around, Code:
$(($y*100%$x)) With a bit of work you can get decimal places from this and concantenate them to get the result. |
I'm not sure if bash (or any other shell) can do arithmetic directly,
but it is certainly possible to give the problem to another process, and return the answer into bash: x=309.0 y=98.0 z=`python -c "print $y / $x * 100"` echo $z Want to use something other than python? Try Perl or expr. |
yea expr works as the poster above said
|
that won't work because $x and $y are already whole numbers and i can't simply add a decimal on the end because they are taken from performing a command. They represent the number of files in a certain directory.
|
Maybe you should look at the bc command. You may need to install it - it did not come automatically installed with Mandrake.
|
Well, you could do
Code:
x=$x+0.0 Code:
z=($y+0.0)/($x+0.0) Quote:
Hope this helps... |
thanks guys,
but I just ended up multipying the numberator by 100 and said 'screw it' to the decimal, i couldn't figure it out, so I just went with rounded number. Thanks again, |
This will give you 2 decimal places if you still interested:
Code:
#!/bin/bash For example, anything from 31.710 to 31.719 will be 31.71 as there is no rounding up. If it needs to be more accurate you can get three decimal places and increment the second decimal place as necessary. |
Thanks very much,
This should prove to be handy in the future. |
All times are GMT -5. The time now is 03:23 AM. |