LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash math...can't divide!! (https://www.linuxquestions.org/questions/programming-9/bash-math-cant-divide-738052/)

vous 07-06-2009 08:07 AM

bash math...can't divide!!
 
I try to make a division like so:

VAR1=$(( 28331 / 33009));
echo "Result is: $VAR1";


It should come out with "Result is 6.05"....but no, it comes with:

$ Result is 0

When I do it with smaller numbers like 100 / 3 it works perfectly. What is the problem?

GazL 07-06-2009 08:17 AM

Quote:

Originally Posted by vous (Post 3598440)
I try to make a division like so:

VAR1=$(( 28331 / 33009));
echo "Result is: $VAR1";


It should come out with "Result is 6.05"....but no, it comes with:

$ Result is 0

When I do it with smaller numbers like 100 / 3 it works perfectly. What is the problem?

The Result isn't 6.5 at all. You're dividing a number by a number greater than itself so it will be 0.something.

The reason you're getting 0 is that the answer is given as a truncated integer.

ghostdog74 07-06-2009 08:22 AM

use awk
Code:

awk 'BEGIN{print 28331 / 33009}'

pixellany 07-06-2009 08:32 AM

Code:

mherring@Ath:~$ echo $((100/3))
33

Hmmmm----not quite perfect........;)

There is a utility for bash that does real decimal math, but I don't remember what it is.

This is easier:
Code:

python
>>> 100./3
33.33333333
>>> 2/3
0
>>>2./3
0.66666666
>>>2/3.
0.66666666

Note how easy it tis to tell it you want integer or decimal math.....

GazL 07-06-2009 08:33 AM

Interesting. I didn't know awk could do math. I'll have to remember that one myself.

ghostdog74 07-06-2009 08:38 AM

Quote:

Originally Posted by GazL (Post 3598475)
Interesting. I didn't know awk could do math. I'll
have to remember that one myself.

please see my sig on link on learning Gawk.

GazL 07-06-2009 08:58 AM

Quote:

Originally Posted by ghostdog74 (Post 3598481)
please see my sig on link on learning Gawk.

Thanks ghost. I'll check those out sometime. I've always tended towards sed rather than awk, so never really gave it much more than a cursory glance.

jf.argentino 07-06-2009 10:44 AM

Maybe easier than gawk, you can invoke "bc" to do floating point arithmetic

jlinkels 07-06-2009 08:46 PM

Code:

echo "4 k 100 3 / p" | dc
or, if you like
Code:

answer=$(echo "4 k 100 3 / p" | dc)
yields: 33.3333

You guessed it, "4 k" determines the number of decimal places.

jlinkels

vous 07-07-2009 03:22 AM

This worked actually, thanks!

echo "scale=5; (54321 / 12345)" | bc


All times are GMT -5. The time now is 03:27 PM.