Tuesday, 15 June 2010

php - Getting different results when adding numbers -


I'm currently adding something simple of decimal numbers to PHP (currency), but for some reason I can add it I get two numbers and get different results.

What I am doing is acquiring some rows in a MySQL table in PHP, adding a total to each receipt and accumulating the result in another MySQL table (10, 2):

  & lt ;? Php foreach ($ query_result as line $) {$ total_receipts = $ total_receipts + $ row ['total']; // My locale requires comma as a decimal separator and as a digit for thousands: Number echo (format) ($ total_receipts, 2, ",", "."); }? & Gt; The strange thing is that I can do the same operation twice on the exact same lines and can get two different results in relation to the decimal point. For example, when I add the following numbers:  
  3621.94 1230.29 1025.00 1025.00  

The correct value of the first 692.223 was inserted in DB. When I went for the second time, the value put in the DB was 6.90. For some reason, deciding to move the decimal point around it for the second time.

I am not using number_format () to insert in the DB, I am storing $ total_receipts without modifications.

Error in this particular example appeared in the second attempt, but sometimes it can show for the first time and may be corrected for the second time. Sometimes I can not even copy the bug.

What am I doing wrong? I am reading about BCmath, but I am not sure that I should use it for this simple addition.

Please use number_format () to insert in DB:

  & lt ;? Php $ total_receipts = 0; // Always start Vars foreach ($ query_result as the $ line) {$ total_receipts + = $ row ['total']; // DB Eco Number-Formatting Method ($ total_receipts, 2, ".", ""); }? & Gt;  

No comments:

Post a Comment