# bc显示小数点前的0

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

#!/bin/bash
#方法1
res1=(printf "%.2f" echo "scale=2;1/3"|bc)
res2=(printf "%.2f" echo "scale=2;5/3"|bc)
#方法2
#v=(echobig 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 isres1
echo res2 is res2
echo v1 isv1
echo v2 is v2
echo mem1 ismem1
echo mem2 is \$mem2

[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

# 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进行进位的。