html tool

2017年12月13日星期三

shell 计算浮点数

http://www.361way.com/linux-bc-point-zero/4960.html



打开bc进入交互模式,我们键入scale=2; 1/3 回车,看到结果0.33前的0没有---注意此处保留小数点人2位 scale=2不能少,少了结果为是0 。
解决方法如下:
  1. #!/bin/bash
  2. #方法1
  3. res1=$(printf "%.2f" `echo "scale=2;1/3"|bc`)
  4. res2=$(printf "%.2f" `echo "scale=2;5/3"|bc`)
  5. #方法2 【popexizhi: 看来还是用awk 比bc 好一点 :)】
  6. #v=$(echo $big $small | awk '{ printf "%0.2f\n" ,$1/$2}')
  7. v1=$(echo 1 3 | awk '{ printf "%0.2f\n" ,$1/$2}')
  8. v2=$(echo 5 3 | awk '{ printf "%0.2f\n" ,$1/$2}')
  9. #方法3
  10. mem1=`echo "scale=2; a=1/3; if (length(a)==scale(a)) print 0;print a "|bc`
  11. mem2=`echo "scale=2; a=5/3; if (length(a)==scale(a)) print 0;print a "|bc`
  12. echo res1 is $res1
  13. echo res2 is $res2
  14. echo v1 is $v1
  15. echo v2 is $v2
  16. echo mem1 is $mem1
  17. echo mem2 is $mem2

没有评论:

发表评论