加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 如何比较shell脚本中的两个浮点值

发布时间:2020-12-14 00:44:22 所属栏目:Linux 来源:网络整理
导读:我不得不在 shell脚本中进行划分,最好的方法是: result1=`echo "scale=3; ($var1 / $total) * 100"| bc -l`result2=`echo "scale=3; ($var2 / $total) * 100"| bc -l` 但我想比较$result1和$result2的值 使用if test $result1 -lt $result2或者如果[$result
我不得不在 shell脚本中进行划分,最好的方法是:

result1=`echo "scale=3; ($var1 / $total) * 100"| bc -l`
result2=`echo "scale=3; ($var2 / $total) * 100"| bc -l`

但我想比较$result1和$result2的值

使用if test $result1 -lt $result2或者如果[$result1 -gt $result2]不起作用:(

知道怎么做吗?

解决方法

您可以使用expr(1)比较浮点数:

: nr@yorkie 3724 ; expr 3.1 '<' 3.3
1
: nr@yorkie 3725 ; expr 3.1 '<' 3.09
0

您还可以让bc进行比较以及计算:

if [ "$(echo $result1 '<' $result2 | bc -l)" -eq 1 ];then ... fi

最后,ksh93可以使用浮点数进行算术求值$(($result1< $result2)),尽管bash不能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读