bash环境下处理float,主要是通过bc命令来完成的,在shell脚本中也可以这样来处理浮点数。
bc - Arbitrary precision calculator language
参数说明:更多详细的信息可以参考man bc页面
[root@rhel6164 ~]# bc -h
usage: bc [options] [file ...]
-h --help print this usage and exit
-i --interactive force interactive mode
-l --mathlib use the predefined math routines
-q --quiet don't print initial banner
-s --standard non-standard bc constructs are errors
-w --warn warn about non-standard bc constructs
-v --version print version information and exit例子:
$var3=`echo "scale=2;$var1/$var2"|bc` 或者 $var3=$(echo "scale=2;$var1/$var2"|bc)
scale表示要保留的位数。可以参考man bc页面得到更多关于scale的信息
[root@rhel6164 ~]# echo "scale=4;4/3" | bc #保留4位有效数字
1.3333
bc能够识别多行表示,也能够识别输入重定向,允许将一个文件重定向到bc命令来处理。
例如,
variable=`bc<<EOFoptions
statements
expressions
EOF
`
[root@rhel6164 bc]# cat bc.sh
#!/bin/bash
variable1=4
variable2=3
variable=`bc<<EOF
scale=4
$variable1/$variable2
EOF
`
echo "$variable1/$variable2=$variable"
[root@rhel6164 bc]# bash bc.sh
4/3=1.3333

在bash环境下处理浮点数,通常借助bc工具来实现。通过设置scale参数来控制精度,如`scale=2`表示保留两位小数。可以使用命令行或shell脚本中的变量赋值来执行浮点数运算,例如 `$var3=$(echo "scale=2;$var1/$var2"|bc)`。bc还支持多行表达式和输入重定向,方便处理复杂计算。
868

被折叠的 条评论
为什么被折叠?



