小数前的0在html不显示,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

打开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时会自动进行进位,具体可以参考维基百科数值修约规则 。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值