Jump to content

Rounding miscalcualtion


dyedblue

Recommended Posts

I have a money vouchering form that users input an invoice amount and select percentages (up to three) that the form calculates the amount from each fund for. It works most of the time but I am being thrown off because of a rounding issue that causes the total of the calculated amounts for the 3 funds not to equal the invoice amount. It is off by $.01.

 

I have the following code and have tried several approaches the latest being to take the sum of the 2nd and 3rd amounts and subtract that from the invoice amount to give me the 1st amount. The 1st amount is still often off by $.01. Is there anyone who has experienced a similar problem that could shed some light on the subject for me or that has an easier approach to my problem?

 

//Calculates the Amounts to be charged to each fund based on percentages entered
$percent = 100;

//Calculates the second fund amount
$percentagecalc2=$percentage2 / $percent;
$amtr2=$amt * $percentagecalc2;
$amt2 = preg_replace('/([\d,]+.\d{2})\d+/', '$1', $amtr2);
$amt2 = number_format($amt2, 2, '.', ',');

//Calculates the third fund amount
$percentagecalc3=$percentage3 / $percent;
$amtr3=$amt * $percentagecalc3;
$amt3 = preg_replace('/([\d,]+.\d{2})\d+/', '$1', $amtr3);
$amt3 = number_format($amt3, 2, '.', ',');

//Calculates the first fund adds penny if needed
$amtr1=$amt-($amtr2+$amtr3);
$amt1 = number_format($amtr1, 2, '.', ',');

Link to comment
Share on other sites

You are rounding before the end of the calculation, which gives the the wrong expected result, the actual result is correct. When you say (279.71 -167.82) = 111.89, that is true, however, the program won't round until the end and it doesn't get 167.82, it gets 167.826, which changes the answer to 111.884, and that rounds down to .88.

Link to comment
Share on other sites

In my code ($amtr1=$amt-($amtr2+$amtr3); I use the pre-rounded numbers ($amtr2, $amtr3) to get the first amount. I am using $amt1, $amt2, $amt3 to display the amounts so I don't want to take off the rounding for them, but as far as I can tell I only use the pre-rounding amounts to do the calculations.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.