tags:

views:

376

answers:

6

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

A: 

Bash doesn't understand floating-point numbers. It only understands integers.

You can either step up to a more powerful scripting language (Perl, Python, Ruby...) or do all the math through bc or similar.

Warren Young
A: 

The bash language is best characterized as a full-featured macro processor, as such there is no difference between numbers and strings. The problem is that test(1) works on integers.

DigitalRoss
Not entirely true. Bourne shell didn't know about integers, but Bash does, through "typeset -i".
Warren Young
A: 

use awk

x="0.80"
y="0.70"
result=$(awk -vx=$x -vy=$y 'BEGIN{ print x>=y?1:0}')
if [ "$result" -eq 1 ];then
    echo "x more than y"
fi
ghostdog74
+1  A: 

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.

A: 

If your values are guaranteed to be in the same form and range, you can do string comparisons:

if [[ $x > 0.70 ]]
then
    echo "It's true"
if

This will fail if x is ".8" (no leading zero), for example.

However, while Bash doesn't understand decimals, its builtin printf can format them. So you could use that to normalize your values.

$ x=.8
$ x=$(printf %.2 $x)
$ echo $x
0.80
Dennis Williamson
+1  A: 

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.

William Pursell