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, '.', ',');