I'm currently doing some simple addition of decimal numbers in PHP (currency), but for some reason I can add the same numbers twice and get different results.
What I'm doing is getting some rows from a MySQL table in PHP, adding the total for each receipt and storing the result in another MySQL table as decimal(10,2):
<?php
foreach($query_result as $row) {
$total_receipts = $total_receipts + $row['total'];
//my locale requires commas as decimal separators and points for thousands:
echo number_format($total_receipts,2,",",".");
}
?>
The strange thing is I can do the same operation twice on the exact same rows and get two different results, with regard to the decimal point. For example, when I add the following numbers:
3621.94
1230.29
1025.00
1025.00
The first time the correct value of 6902.23 was inserted in the DB. When I ran it the second time, the value inserted in the DB was 6.90. For some reason, the second time around it decided to move the decimal point.
I'm not using number_format() to insert in to the DB , I'm storing $total_receipts without modifications.
In this particular example the error appeared in the second try, but sometimes it can show up the first time and the second time be correct.Sometimes I cannot even replicate the bug.
What am I doing wrong? I've been reading about bcmath, but I'm not sure if I should be using it for this simple addition.