Reputation: 32336
How do I convert a string to a number? The following Bash script does not work as expected.
#!/bin/sh
mynum="0.02"
if [[ $mynum -lt 1 ]];then
echo "low"
else
echo "high"
fi
Error message
stack.sh: line 5: [[: 0.02: syntax error: invalid arithmetic operator (error token is ".02")
Upvotes: 2
Views: 1107
Reputation: 51
You can use "<"">" instead of -lt
or -gt
. For example:
a=0.09;[[ $a < 1 ]] && echo low ||echo big
low
a=1.01;[[ $a < 1 ]] && echo low ||echo big
big
Upvotes: -2
Reputation: 5728
The following worked for me. It's just the idea how you can use bc. Change the code as you wish.
mynum="1.02"
d=\`echo "$mynum-1" | bc\`
if [ "${d:0:1}" = "-" ]
then
echo "low"
else
echo "high"
fi
Upvotes: 2
Reputation: 61389
The problem is that bash
normally only supports integer arithmetic; you will need to punt floating or complex math to dc
or bc
.
You may be able to cheat in this case:
case $mynum in
0 | 0.* | .* | -*)
echo low
;;
*)
echo high
;;
esac
But this obviously isn't generally applicable.
Upvotes: 3