0

Hey guy's I am working on a project of mine which involves the use of money. I am trying to not use round anymore because, it's rounding things to nearest tenth and I need exact numbers. One reason I was using it, was because it was giving a whole number.

The way I am working my number system is that 100 = $1, 2000 = $20, etc.. I was currently using the round function because it would get rid of the decimal point for me and give me a whole number, lets say: 223 which in turn would = $2.23.

Here is what I am using:

$amount += round(($amount / 29) + 30);

Here are the numbers:

Lets say we have a charge of 100 and we add 125 which equal 225 (USD $2.25). Now we add taxes and processing: + 2.9% + $.30. After multiplying 2.25 by 2.9% and adding .30 the amount would be: 0.36525 - this is the amount that should be added than to the $2.25 which than would be 261 = $2.61

The issue is because of the rounding, when I look in my Stripe panel (I am using Stripe API for payments) I see a charge of $2.63. So my question is, how would I go about making it exact without having any rounding and decimal places.

UPDATE:

Here is the above example more explained:

Lets say we have a charge of 100 and we add 125 which equal 225 (USD $2.25). Now we add taxes and processing: + 2.9% + $.30. After multiplying 2.25 by 2.9% and adding .30 the amount would be: 0.36525 - this is the amount that should be added than to the $2.25 which than would be 261 = $2.61

So now with that the actual value of amount that should be charged is $2.61 but instead when using the round it gives me 263 which also means $2.63. The above example is the simple math that is correct.

4

2 回答 2

2

为了避免这样的计算打嗝,只对最终结果进行四舍五入。保持所有其他计算尽可能准确:

$original = 100;
$original += 125;

$tax = $original * 2.9 / 100; //+2.9%
$tax += 30; //+$.30

$original += $tax; //Add tax.

echo $original; //Result is 261.525. Round as you please.
于 2013-07-21T18:41:18.527 回答
0

您可以指定精度和舍入方法以保持一致(PHP round()),然后您可以处理实际值。从长远来看,做像乘以 10 的倍数这样的数学技巧只会让它变得更加混乱。

$amount += round(($amount / 29) + 30, 2, PHP_ROUND_HALF_UP);

这会解决你的问题吗?

于 2013-07-21T18:39:35.650 回答