1

In bash,I am trying to do math with a integer and a float number to get a integer result. below code snippet doesn't work:

x=25
y=0.2
z=$((x*y))
echo $x*$y=$z

The error message is:

sh: line 3: 0.2: syntax error: invalid arithmetic operator (error token is ".2")

If both variable is integer, it works fine.

How can I get "25*0.2=5" from bash script?

1
  • 3
    bash doesn't support floating point arithmetic. Use bc or awk or perl Commented Jul 5, 2017 at 20:48

2 Answers 2

2

Place your printout in quotes in echo. Also your z=$((x*y)) will make z empty or error:

25*0.2: syntax error: invalid arithmetic operator (error token is ".2")

So... Here is tested code and might be like this:

x=25
y=0.2
z=$(echo $x*$y | bc)
echo "$x*$y=$z"

result will be like this:

25*0.2=5.0

Note: we used bc command for z calculation

Sign up to request clarification or add additional context in comments.

Comments

0

Try bashj (a bash mutant with java support) https://sourceforge.net/projects/bashj/.

for instance:

#!/usr/bin/bashj
echo Math.cos(0.5)
echo Math.hypot(3.0,4.0)

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.