LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Multiply floats in bash script (https://www.linuxquestions.org/questions/linux-software-2/multiply-floats-in-bash-script-618691/)

mkrems 02-04-2008 06:00 PM

Multiply floats in bash script
 
I have a bash script with the following line where $timestep is a decimal number.

t=$timestep*$i

echo $t gives the value "0.125*2" for example instead of "0.250".
How do I change this?!?

bigrigdriver 02-04-2008 06:25 PM

Try t=`expr $timestep*$i`.

Also, see the Advanced Bash Scripting Guide, chapter 15 on arthmetic expansion.

jailbait 02-04-2008 06:28 PM

Quote:

Originally Posted by mkrems (Post 3046105)
I have a bash script with the following line where $timestep is a decimal number.

t=$timestep*$i

echo $t gives the value "0.125*2" for example instead of "0.250".
How do I change this?!?

bash does not have floating point arithmetic. Any variable with a decimal point in it is treated as a string. So bash processes t=$timestep*$i as the concatenation of three strings. The strings are:
$timestep=0.125
*
$i=2

You are not going to get bash to use 0.125 as a number in an arithmetic expression.

--------------------
Steve Stites

colucix 02-04-2008 06:33 PM

To do floating point calculations in a shell script you can invoke awk, e.g.
Code:

timestep=0.125
i=2
t=$(echo $timestep $i | awk '{printf "%4.3f\n",$1*$2}'

or you can use bc calculations (see man bc for details).

mkrems 02-04-2008 06:51 PM

hey guys, thanks for the help but actually i figured it out to be:

t=$(expr $timestep*$i | bc)

i have not tried the awk method, but the other ones did not work for me.

colucix 02-04-2008 07:10 PM

It should be
Code:

t=$(echo $timestep*$i | bc)
expr is a command who evaluates arithmetic expressions, while you have to simply echo the arithmetic expression to the bc calculator.


All times are GMT -5. The time now is 08:37 AM.