【发布时间】:2014-10-13 05:29:57
【问题描述】:
我正在编写一个处理计算美元金额的脚本,我想知道这样做的正确方法或建议方法是什么。
我处理的是美元和美分,而不是美分。我看过such as this 的帖子,其中给出了需要小数美分的场景,例如股票。我认为我不需要那种精确度,但在我驳回它之前,我想要一些建议。
假设我以 9.99 美元的价格出售一件商品,税率为 6.5%。
$item_cost = 9.99;
$tax_percent = 0.0650; //6.5%
$tax = $item_cost * $tax_percent;
//tax is 0.38935
$total = $item_cost + $tax;
//total is 6.37935
我不能向用户收取 6.37935 美元的费用。我只是在处理美元和美分。示例继续...
$total = 4.401433
$rounded_total = round($total,2);
echo $rounded_total;
//rounded total is 4.4
虽然我知道 4.4 美元与 4.40 美元相同,但我无法通过我的支付处理器运行它。先四舍五入到小数点后两位,然后将数字格式应用到小数点后两位“安全”吗?
$total = 4.401433
$rounded_total = round($total,2);
$formatted_total = number_format($rounded_total,2,'.','');
echo $formatted_total;
//rounded and formatted total is 4.40
通过先四舍五入到小数点后 2 位然后使用数字格式确保四舍五入的数字确实是小数点后 2 位来确定应付金额是否“可接受”?
【问题讨论】:
-
我自己用这种方法支付运费(基于物品重量)
-
两者都是一样的,所以你可以毫无问题地使用它......
-
此问题属于 Stack Exchange 网络中的另一个站点:codereview.stackexchange.com
标签: php