LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash, non-integers and arithmetic (https://www.linuxquestions.org/questions/programming-9/bash-non-integers-and-arithmetic-72520/)

causticmtl 07-14-2003 02:33 AM

Bash, non-integers and arithmetic
 
Why is this happening?

$ let total+="4.5"; echo $total
-sh: let: total+=4.5: syntax error in expression (error token is ".5")
4

I need the variable to hold a non-integer. What's the workaround? I've read quite a few tutorials on the net concerning arithmetic and variables and the answer I keep getting is this one:

Quote:

if i ran "echo $[3/4]" at the command prompt, it would return 0 because bash only uses integers when answering. If you ran "echo 3/4|bc -l", it would properly return 0.75.
... yet if I do:

$ let total+=4.5|bc -l; echo $total

I get:

-sh: let: total+=4.5: syntax error in expression (error token is ".5")
4

What is the proper syntax?

Are there more comprehensive tutorials than the ones I have encountered?

TheLinuxDuck 07-14-2003 08:26 AM

The problem is the definition of total. The code will need to echo 3/4 then pipe through bc -l, as:
Code:

total=`echo "3/4" | bc -l`
echo "total: $total"

which returns .75000000000000000000 on my system. (=

causticmtl 07-15-2003 12:15 AM

Thanks Linux Duck,

How would I get BASH to return only the first two digits after the decimal, essentially giving a result of .75? Is there a command which could restrict output to a "dollar" notation?

i.e. total=.75 or total=2.50 or total=21.25

Thanks again for your help.

TheLinuxDuck 07-15-2003 08:31 AM

Sure! There are several methods of doing so. One is to adjust the scale (number of decimal places that bc keeps). You could change the bc line to:
Code:

total=`echo "scale=2; 3/4" | bc -l`;
which returns
Code:

~/shell/casticmtl> ./math.sh
total is .75

That will solve it. Or, printf will do it, and make it a bit more friendly, as far as display money value goes. Change the echo to something like:

Code:

printf "total is \$%0.2g\n" $total
which outputs
Code:

~/shell/casticmtl> ./math.sh
total is $0.75

Just in case you're not familiar with the format, %g is the format for displaying a double, .2 will cause it to retain only the first two decimal places, and the 0 will cause it to be padded with zero's.

That should do it!!

Mons 07-16-2003 07:36 AM

Hello Linux Duck:
I tried
:printf "total is \$%0.2f\n" $total:
The output is
total is $0.00
.75000000000000000000$
Could you please explain this?
Thanking you,
Mons...

TheLinuxDuck 07-16-2003 09:15 AM

mons:

try changing the 'f' to 'g'. Also, can you post the script, just so I can see what it's doing?

TLD


All times are GMT -5. The time now is 03:35 AM.