shell中的浮点计算

两种方法:

1. bc命令

2. awk命令

一: bc命令

wsj@linux17:~> a=4.1 b=9.233

wsj@linux17:~>echo "$a + $b" | bc
13.333
wsj@linux17:~> echo "$a*$b" |bc
37.855


限定精确度:

wsj@linux17:~> echo "scale=4;$a*$b/2"|bc
18.9276


注:scale=4 表示精确到小数后4位 浮点比较大小在shell中,无法对两个小数直接的进行比较,一种方法是使用bc命令

wsj@linux17:~> a=4.1 b=9.233
wsj@linux17:~> if [ `echo "scale=4;$a > ($b/2)"|bc` -eq 1 ]; then echo "a greater b/2"; else echo "b/2 greater than a";fi
b/2 greater than a  


注:如果没有scale=4,表示不指定,则按照int处理

wsj@linux17:~>if [ `echo "$a > ($b/2)"|bc` -eq 1 ]; then echo "a greater b/2"; else echo "b/2 greater than a";fi
a greater b/2


二:awk命令

wsj@linux17:~> a=4.1 b=9.233wsj@linux17:~> echo  $a $b | awk '{if($1>$2){printf"%.3f greater then %.3f\n",$1,$2}else{printf"%.3f less then %.3f\n",$1,$2}}'
4.100 less then 9.233


 


 


 


 

你可能感兴趣的:(shell中的浮点计算)