15

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

PJT
  • 3,439
  • 5
  • 29
  • 40

6 Answers6

18

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.

ghostdog74
  • 327,991
  • 56
  • 259
  • 343
4

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"
fi

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
Alfe
  • 56,346
  • 20
  • 107
  • 159
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
3

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
  • 204,365
  • 48
  • 270
  • 300
2

Here is my simple solution:

 BaseLine=70.0         
 if [ $string \> $BaseLine ]
 then
      echo $string
 else
      echo "TOO SMALL"
 fi
Haimei
  • 12,577
  • 3
  • 50
  • 36
1

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
  • 327,991
  • 56
  • 259
  • 343
  • Very cleaver. Works better than bc. It allowed me to use variables, which was a requirement, not static numbers. Thank you. Simple and clear. I had to learn bc to use it, needed a quick and easy solution! Thank you! – jewettg Jul 25 '16 at 15:28
0

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
  • 143,651
  • 25
  • 248
  • 329