因此,当用户输入像4750这样的4位数字时,程序必须转换该两位小数,而不是将该数字转换为47.50美元。这将存储在cost_in_cents中。这是我到目前为止只是计算的代码。消息已经在不同的函数上打印了,我只需要帮助编码带有十进制数的计算。
#!/usr/bin/env bash
Percent=20
Numguests=DO_NOT_CHANGE # number of elements in ${GUESTS}
Limit=DO_NOT_CHANGE # $num_guests * $BUDGET_PER_PERSON
Cost=DO_NOT_CHANGE # prompt user
Tip=DO_NOT_CHANGE # $cost * $percent%
Totalcost=DO_NOT_CHANGE # $cost + $tip
Averagecost=DO_NOT_CHANGE # $overall_cost / $num_guests
function calc {
echo -n "What is the total cost in cents (not including tip)? ";
read cost_in_cents
Numguests=8
Limit=$((8 * 25))
Cost=$cost_in_cents #needs to convert into decimal
Tip=$(($Cost * $Percent)) #needs to be in decimal
Overall_cost=$(($Cost + $Tip)) #needs to have decimal
Average_cost=$(($Totalcost /8)) #needs to be in decimal
}
如何将cost_in_cents转换为小数点后两位(如果数字为4315,则将其转换为$ 43.15或如果数字为50则实际为$ 0.50)并将其相乘而不将其四舍五入
答案 0 :(得分:0)
你可以在bc中做数学,但即使在awk中也是如此:
$ cost="3444"
$ cost2=$(awk '{print $0/100}' <<<"$cost")
$ echo "$cost ==> $cost2"
3444 ==> 34.44
答案 1 :(得分:0)
您可以直接在awk
中执行此操作和许多其他计算。这是一个例子......
value=4315; cost=$(awk "BEGIN{print $value/100}"); echo $cost
43.15
如果要控制十进制数更改为printf \"%.2f\n\", $value/100