5

Script:

#!/bin/bash
vpct=5.3 
echo $((vpct*15))    

Error:

./abc.sh: line 5: 5.3: syntax error: invalid arithmetic operator (error token is ".3")

I know I don't need a script to multiply 5.3 * 15, but this small script to single out the error. Please advise.

6 Answers 6

8

According to http://www.softpanorama.org/Scripting/Shellorama/arithmetic_expressions.shtml:

Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings.

You should use bc to perform such calculations, just as in dogbane's solution, except that you should escape the expression using quotes so the * character doesn't cause unwanted shell expansion.

echo "$vpct*15" | bc
Sign up to request clarification or add additional context in comments.

Comments

3

Besides bc, there are other tools you can tools you can try

awk -v vpct="$VPCT" 'BEGIN{print vpct * 15}'

echo $vpct | ruby -e 'print gets.to_f * 15 '

echo  "$vpct 15 * p" | dc

1 Comment

Since you are listing alternatives, if you use zsh instead of bash the script will simply work.
3

You should use bc for floating point arithmetic:

echo "$vpct*15" | bc

Comments

0

$(( $vpct * 15 )) // (add a $ sign should do it)

4 Comments

--sorry I cannot try these solution, but will be happy if one of these works out for you :)
./abc.sh: line 5: 5.3*15 : syntax error: invalid arithmetic operator (error token is ".3*15 ") Neither work
sorry Humble and dogbane - at least above is a link to the same problem
Dollar signs aren't necessary in an arithmetic context in Bash.
0

Shebang should be written like #! And anyway $(()) is only for integers.

Comments

0

If you have ksh available, it will do float arithmetic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.