Monday, 22 May 2017

rounding - PHP: precision in mathematical operations

i've a question on PHP and mathematical operations.



why 9000.05 - 9000 return 0.049999999999272 and not 0.05 ???



please look that example



function calculate ( $financed, $months, $rate){
$installment = 782.90;
$rate= $rate / 100;

$delta = 0;

$OUT = $financed;
$IN = 0;

for ($t = 1; $t <= $months; $t++){
echo "installment $t \n";
$installment_act = $installment / pow((1 + ($rate / 12)), $t);
$installment_act = round($installment_act, 2);
echo "installment actualized $installment_act \n\n";

$IN += $installment_act;
echo "\t\t\t\t $IN\n";
}
echo "\n IN ($IN) - OUT ($OUT) = ";
$delta = $IN - $OUT;
echo "delta = $delta\n ";
}

calculate(9000, 12, 8);


//RESULT

installment 1
installment actualized 777.72

777.72
installment 2
installment actualized 772.56

1550.28

installment 3
installment actualized 767.45

2317.73
installment 4
installment actualized 762.37

3080.1
installment 5
installment actualized 757.32


3837.42
installment 6
installment actualized 752.3

4589.72
installment 7
installment actualized 747.32

5337.04

installment 8
installment actualized 742.37

6079.41
installment 9
installment actualized 737.45

6816.86
installment 10
installment actualized 732.57


7549.43
installment 11
installment actualized 727.72

8277.15
installment 12
installment actualized 722.9

9000.05


IN (9000.05) - OUT (9000) = delta = 0.049999999999272


as you see $IN - $OUT return a wrong result, why? and how could i fix it?



thanks advance for any suggestion
Michele

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...