所以当我编码时我试图让输出打印出 0.12 而不是 0.12。下面是我的代码
echo -n "What is the total cost? ";
read cents
cost=$(echo "scale =2;$cost_in_cents/100" | bc);
percent=$(echo "scale =2;$percent / 100" | bc);
tip=$(echo "scale =2;$cost*$percent" | bc);
overall_cost=$(echo "scale =2;$cost+$tip" | bc);
average_cost=$(echo "scale =2;$overall_cost/${#GUESTS[@]}" | bc);
输出再次给出了 0.12 的正确输出,但我需要在小数点前加一个零。提前致谢!
答案1
value=$(printf "%3.2f\n" $(echo "scale=2; 12 / 100" | bc))
答案2
像这样的东西:
$ a=$(echo "0.1 + 0.1" | bc) && echo "$a"
.2
$ a=$(printf '0%s\n' "$a") && echo $a
0.2
选择:
$ echo "0.1 0.1" | awk '{printf "%.2f\n", $1 + $2}'
0.20
答案3
Bash 有 printf。您可以执行类似printf '%.2f' $cents
打印四舍五入到小数点后两位的操作。如果想将其赋值给变量,则使用-v
或使用$()
结构体。