如何在 bash 中使用 bc 四舍五入小数?

如何在 bash 中使用 bc 四舍五入小数?

以下是我想要使用 Bash 脚本的一个简单示例:

#!/bin/bash
echo "Insert the price you want to calculate:"
read float
echo "This is the price without taxes:"
echo "scale=2; $float/1.18" |bc -l
read -p "Press any key to continue..."
bash scriptname.sh

假设价格为:48.86 答案将是:41.406779661(实际上是 41.40 因为我使用的是scale=2;

我的问题是: 我如何四舍五入小数点后第二位才能以这种方式显示答案?:41.41

答案1

最简单的解决方案:

printf %.2f $(echo "$float/1.18" | bc -l)

答案2

bash 的一个 round 函数:

round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};

在您的代码示例中使用:

#!/bin/bash
# the function "round()" was taken from 
# http://stempell.com/2009/08/rechnen-in-bash/

# the round function:
round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};

echo "Insert the price you want to calculate:"
read float
echo "This is the price without taxes:"
#echo "scale=2; $float/1.18" |bc -l
echo $(round $float/1.18 2);
read -p "Press any key to continue..."

祝你好运:o)

答案3

Bash/awk 四舍五入:

echo "23.49" | awk '{printf("%d\n",$1 + 0.5)}'  

如果你有 python,你可以使用如下命令:

echo "4.678923" | python -c "print round(float(raw_input()))"

答案4

这是脚本的缩写版本,已修复以提供您想要的输出:

#!/bin/bash
float=48.86
echo "You asked for $float; This is the price without taxes:"
echo "scale=3; price=$float/1.18 +.005; scale=2; price/1 " | bc

请注意,向上舍入到最接近的整数相当于加 .5 并取整数倍,或向下舍入(对于正数)。

此外,比例因子在操作时应用;所以(这些是bc命令,您可以将它们粘贴到终端中):

float=48.86; rate=1.18; 
scale=2; p2=float/rate
scale=3; p3=float/rate
scale=4; p4=float/rate
print "Compare:  ",p2, " v ", p3, " v ", p4
Compare:  41.40 v 41.406 v 41.4067

# however, scale does not affect an entered value (nor addition)
scale=0
a=.005
9/10
0
9/10+a
.005

# let's try rounding
scale=2
p2+a
41.405
p3+a
41.411
(p2+a)/1
41.40
(p3+a)/1
41.41

相关内容