16

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
    0.70, and 0.80, are not integers. Commented Nov 23, 2009 at 23:53

6 Answers 6

19

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.

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

2 Comments

bc <<<"0.8 > 0.7" does it with less overhead.
It looks like bc is not always available out-of-the-box, like in Docker containers
5

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

Comments

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.

Comments

2

Here is my simple solution:

 BaseLine=70.0         
 if [ $string \> $BaseLine ]
 then
      echo $string
 else
      echo "TOO SMALL"
 fi

Comments

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

1 Comment

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!
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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.