在linux中不能在shell中直接计算浮点数,可以用bc或者awk来达到同样效果

1. 用bc来实现,bc中设置scale的参数值来设定保留小数点的位数

[root@hadoop ~]# n1=6
[root@hadoop ~]# n2=5
[root@hadoop ~]# echo "scale=2;${n1}/${n2}"|bc
1.20
[root@hadoop ~]# echo "scale=2;1/2"|bc
.50
[root@hadoop ~]#


[root@hadoop ~]# a=$(echo "scale=2;15/10"|bc)
[root@hadoop ~]# echo ${a}
1.50


如果计算的结果小于0则不显示小数点前的0,可以用以下方式转换

[root@hadoop ~]# echo 'scale=2;a=5/19;if( length(a) == scale(a)) print 0;print a,"\n"'|bc
0.26



2. 用awk来实现

[root@hadoop ~]# n1=6
[root@hadoop ~]# n2=5
[root@hadoop ~]# awk -v m1=$n1 -v m2=$n2 'BEGIN{print m1/m2}'
1.2


Logo

更多推荐