bc是强大而常用的计算工具。不过在除法运算时,如果得到的结果值小于1,得到的小数前面的0不存。本篇提供几个常用小数点前缺0的解决方法。
- [root@361way ~]# bc
- bc 1.06.95
- Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
- This is free software with ABSOLUTELY NO WARRANTY.
- For details type `warranty'.
- scale=2; 1/3
- .33
打开bc进入交互模式,我们键入scale=2; 1/3 回车,看到结果0.33前的0没有---注意此处保留小数点人2位 scale=2不能少,少了结果为是0 。
解决方法如下:
- #!/bin/bash
- #方法1
- res1=$(printf "%.2f" `echo "scale=2;1/3"|bc`)
- res2=$(printf "%.2f" `echo "scale=2;5/3"|bc`)
- #方法2
- #v=$(echo $big $small | awk '{ printf "%0.2f\n" ,$1/$2}')
- v1=$(echo 1 3 | awk '{ printf "%0.2f\n" ,$1/$2}')
- v2=$(echo 5 3 | awk '{ printf "%0.2f\n" ,$1/$2}')
- #方法3
- mem1=`echo "scale=2; a=1/3; if (length(a)==scale(a)) print 0;print a "|bc`
- mem2=`echo "scale=2; a=5/3; if (length(a)==scale(a)) print 0;print a "|bc`
- echo res1 is $res1
- echo res2 is $res2
- echo v1 is $v1
- echo v2 is $v2
- echo mem1 is $mem1
- echo mem2 is $mem2
这里提供了三种方法,其中第方法1、方法3使用的bc处理,方法2使用的awk处理。执行输出结果我们看下:
- [root@361way shell]# sh bc_point_zero.sh
- res1 is 0.33
- res2 is 1.66
- v1 is 0.33
- v2 is 1.67
- mem1 is 0.33
- mem2 is 1.66
三种方法我们可以看到,方法1、方法3对小数点后面的值不会四舍五入,而方法2(awk)方法使用printf 时会对小数点(浮点运算)的值四舍五入进位。所以浮点运行时还是建议使用awk处理。不过在取整数时,awk默认也是不会四舍五入的。
- # echo 5 3 | awk '{ printf "%d\n" ,$1/$2}'
- 1
- # echo 5 3 | awk '{ printf "%d\n" ,$1/$2+0.5}'
- 2
- # echo 4 3 | awk '{ printf "%d\n" ,$1/$2+0.5}'
- 1
awk在取整数运算时,是需要加0.5进行进位的。
注:没有进位其实和小数点后保留的位数有关的,在小数点后的位数大于4时会自动进行进位,具体可以参考维基百科数值修约规则 。