简体   繁体   中英

Using round() to get exact value - PHP

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.

In order to avoid calculation hiccups like that, only round the final result. Keep all other calculations as accurate as possible:

$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.

You can specify precision and rounding method to keep it consistent ( PHP round() ), then you can deal with the actual values. Doing math tricks like multiplication by a multiple of 10 will only make it more confusing in the long run.

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

Will this solve your problem?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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