Linux学习4之shell脚本中的小数运算

时间:2024-11-10 13:54:14


hadoop@Mcnode1:~/cloud/adam/xubo/data/test20160310/test$ cat  
#!/bin/bash
echo `awk -v x=2.45 -v y=3.123 'BEGIN{printf "%.2f\n",x*y}'`
s=1.5
echo $s
echo `awk -v x=2.45 -v y="$s" 'BEGIN{printf "%.2f\n",x*y}'`

结果:

hadoop@Mcnode1:~/cloud/adam/xubo/data/test20160310/test$ ./ 
7.65
1.5
3.68

可以从外部获取变量,也可以自定义变量


2.|bc

hadoop@Mcnode1:~/cloud/adam/xubo/data/test20160310/test$ cat  
#!/bin/bash
echo `awk -v x=2.45 -v y=3.123 'BEGIN{printf "%.2f\n",x*y}'`
s=1.5
echo $s
echo `awk -v x=2.45 -v y="$s" 'BEGIN{printf "%.2f\n",x*y}'`
#product=`awk -v x=2.45 -v y="$s" 'BEGIN{printf "%.2f\n",x*y}'`

s2=$(echo "scale=3; 6 / 5"  | bc)
echo $s2

s3=$(echo "scale=3; $s / 5"  | bc)
echo $s3
结果:

hadoop@Mcnode1:~/cloud/adam/xubo/data/test20160310/test$ ./ 
7.65
1.5
3.68
1.200
.300