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:
$ 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? |
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` |
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. |
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`; Code:
~/shell/casticmtl> ./math.sh Code:
printf "total is \$%0.2g\n" $total Code:
~/shell/casticmtl> ./math.sh That should do it!! |
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... |
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. |