在 bash 中有条件的浮动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2683064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Float conditional in bash
提问by Open the way
in bash I need to compare two float numbers, one which I define in the script and the other read as paramter, for that I do:
在 bash 中,我需要比较两个浮点数,一个是我在脚本中定义的,另一个是作为参数读取的,为此我这样做:
if [[ $aff -gt 0 ]]
then
a=b
echo "xxx "$aff
#echo $CX $CY $CZ $aff
fi
but I get the error:
但我收到错误:
[[: -309.585300: syntax error: invalid arithmetic operator (error token is ".585300")
[[: -309.585300: 语法错误:算术运算符无效(错误标记为“.585300”)
What is wrong?
怎么了?
Thanks
谢谢
采纳答案by ghostdog74
use awk
使用 awk
#!/bin/bash
num1=0.3
num2=0.2
if [ -n "$num1" -a -n "$num2" ];then
result=$(awk -vn1="$num1" -vn2="$num2" 'BEGIN{print (n1>n2)?1:0 }')
echo $result
if [ "$result" -eq 1 ];then
echo "$num1 greater than $num2"
fi
fi
回答by yabt
Using bc instead of awk:
使用 bc 而不是 awk:
float1='0.43255'
float2='0.801222'
if [[ $(echo "if (${float1} > ${float2}) 1 else 0" | bc) -eq 1 ]]; then
echo "${float1} > ${float2}"
else
echo "${float1} <= ${float2}"
fi
回答by Joachim Sauer
Both test(which is usually linked to as [)and the bash-builtin equivalent only support integer numbers.
两者test(通常链接到 as [)和bash-builtin 等效项仅支持整数。
回答by jonretting
Use bc to check the math
使用 bc 检查数学
a="1.21231"
b="2.22454"
c=$(echo "$a < $b" | bc)
if [ $c = '1' ]; then
echo 'a is smaller than b'
else
echo 'a is larger than b'
fi
回答by Guillaume Belanger
The simplest solution is this:
最简单的解决方案是这样的:
f1=0.45
f2=0.33
if [[ $f1 > $f2 ]] ; then echo "f1 is greater then f2"; fi
which (on OSX) outputs:
其中(在 OSX 上)输出:
f1 is greater then f2
Here's another example combining floating point and integer arithmetic (you need the great little perl script calc.pl that you can download from here):
这是结合浮点和整数算法的另一个示例(您需要可以从这里下载的很棒的小 perl 脚本 calc.pl ):
dateDiff=1.9864
nObs=3
i=1
while [[ $dateDiff > 0 ]] && [ $i -le $nObs ]
do
echo "$dateDiff > 0"
dateDiff=`calc.pl $dateDiff-0.224`
i=$((i+1))
done
Which outputs
哪些输出
1.9864 > 0
1.7624 > 0
1.5384 > 0
回答by ndim
I would use awk for that:
我会为此使用 awk:
e=2.718281828459045
pi=3.141592653589793
if [ "yes" = "$(echo | awk "($e <= $pi) { print \"yes\"; }")" ]; then
echo "lessthanorequal"
else
echo "larger"
fi

