Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In BASH convert a string with . in float

I have a string that represent a float:

echo $NUM
5.03

I need to multiply this number for MEGA. If I do it directly:

MEGA="1000"
result=$(($NUM*$MEGA))

I receive an error:

syntax error: invalid arithmetic operator (error token is ".03 * 1000")
like image 377
user3472065 Avatar asked Dec 15 '15 10:12

user3472065


1 Answers

Bash only has integers, no floats. You'll need a tool like bc to properly assign the value of result:

result=$(bc -l <<<"${NUM}*${MEGA}")

Or you can use awk:

result=$(awk '{print $1*$2}' <<<"${NUM} ${MEGA}")
like image 110
chaos Avatar answered Sep 27 '22 21:09

chaos