我想要使用 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
Run Code Online (Sandbox Code Playgroud)
假设价格是:48.86 答案将是:41.406779661(实际上是 41.40 因为我正在使用scale=2;)
我的问题是: 我如何舍入第二个小数以这种方式显示答案?:41.41
mig*_*gas 35
最简单的解决方案:
printf %.2f $(echo "$float/1.18" | bc -l)
Run Code Online (Sandbox Code Playgroud)
小智 34
bash 轮函数:
round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};
Run Code Online (Sandbox Code Playgroud)
在您的代码示例中使用:
#!/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..."
Run Code Online (Sandbox Code Playgroud)
祝你好运:o)
zub*_*ber 22
Bash/awk 舍入:
echo "23.49" | awk '{printf("%d\n",$1 + 0.5)}'
Run Code Online (Sandbox Code Playgroud)
如果你有 python,你可以使用这样的东西:
echo "4.678923" | python -c "print round(float(raw_input()))"
Run Code Online (Sandbox Code Playgroud)
小智 7
这是一个纯粹的 bc 解决方案。舍入规则:在 +/- 0.5 处,从零开始舍入。
将您要查找的比例放在 $result_scale 中;你的数学应该是 $MATH 在 bc 命令列表中的位置:
bc <<MATH
h=0
scale=0
/* the magnitude of the result scale */
t=(10 ^ $result_scale)
/* work with an extra digit */
scale=$result_scale + 1
/* your math into var: m */
m=($MATH)
/* rounding and output */
if (m < 0) h=-0.5
if (m > 0) h=0.5
a=(m * t + h)
scale=$result_scale
a / t
MATH
Run Code Online (Sandbox Code Playgroud)
小智 5
这是脚本的缩写版本,已修复以提供您想要的输出:
#!/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
Run Code Online (Sandbox Code Playgroud)
请注意,向上舍入到最接近的整数相当于加上 0.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
Run Code Online (Sandbox Code Playgroud)