In bash shell script how do I convert a string to an number


Question

Hey I would like to convert a string to a number

x="0.80"

#I would like to convert x to 0.80 to compare like such:
if[ $x -gt 0.70 ]; then

echo $x >> you_made_it.txt 

fi 

Right now I get the error integer expression expected because I am trying to compare a string.

thanks

1
12
11/23/2009 11:49:39 PM

Accepted Answer

For some reason, this solution appeals to me:

if ! echo "$x $y -p" | dc | grep > /dev/null ^-; then
  echo "$x > $y"
else
  echo "$x < $y"
fi

You'll need to be sure that $x and $y are valid (eg contain only numbers and zero or one '.') and, depending on how old your dc is, you may need to specify something like '10k' to get it to recognize non-integer values.

3
11/24/2009 8:23:53 AM

you can use bc

$ echo "0.8 > 0.7" | bc
1
$ echo "0.8 < 0.7" | bc
0
$ echo ".08 > 0.7" | bc
0

therefore you can check for 0 or 1 in your script.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon