简体   繁体   English

PHP:四舍五入至最接近的0.05货币值

[英]PHP: round up to the nearest 0.05 monetary values

I am trying to solve this problem: 我正在尝试解决这个问题:

When I purchase items I receive a receipt which lists the name of all the items and their price (including tax), finishing with the total cost of the items, and the total amounts of sales taxes paid. 当我购买物品时,我会收到一张收据,上面列出了所有物品的名称及其价格(含税),最后列出了物品的总成本以及所支付的营业税总额。 The rounding rules for sales tax are that for a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest 0.05) amount of sales tax. 营业税的四舍五入规则是,对于n%的税率,p的货架价格包含(np / 100四舍五入至最接近的0.05)营业税额。

So, ... I have a price in php: 所以,...我在php中有一个价格:

$value = 11.25;

and I don't understand why 我不明白为什么

var_export(ceil($value * 0.05 * 10));

returns 6 and dividing per 10, the result is 返回6并除以10,结果是

var_export(ceil($value * 0.05 * 10) / 10);

0.59999999999999998 0.59999999999999998


some nice experiments: 一些不错的实验:

php > echo bcmul(11.25, 0.05, 3);
0.562
php > echo bcmul(ceil(11.25), 0.05, 3);
0.60

You could read what bishop point out and also you could read this in order to understand what is the problem. 您可以阅读主教指出什么,你也可以阅读这个以了解是什么问题。

Now talking about a solution, you could use PHP BCMath extension which should be used when you want to work with precision mathematical numbers 现在讨论解决方案时,您可以使用PHP BCMath扩展,当您要使用精确数学数时应使用扩展

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings. 对于任意精度数学,PHP提供了二进制计算器,该计算器支持任意大小和精度的数字,以字符串表示。

One solution (a ugly one) could be this 一个解决方案(一个丑陋的)可能是这样

$value = 11.25;

var_export(bcdiv(ceil($value * 0.05 * 10), 10, 1)); // Output '0.6'

Here I am using the bcdiv from the mentioned extension. 在这里,我正在使用上述扩展名中的bcdiv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM