PHP returns incorrect total

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

ITI
New php-forum User
New php-forum User
Posts: 2
Joined: Wed Nov 07, 2012 8:28 am

PHP returns incorrect total

Postby ITI » Wed Nov 07, 2012 9:18 am

When adding a list of new subTotals to a running total PHP suddenly returns a weird value.

Here is the output I have generated. Have a look at line 36:
1 The current total '0' (integer) + new subTotal '-25969.65' type(double) = new total '-25969.65'
2 The current total '-25969.65' (double) + new subTotal '239.6' type(double) = new total '-25730.05'
...
35 The current total '-163.89' (double) + new subTotal '60.95' type(double) = new total '-102.94'
36 The current total '-102.94' (double) + new subTotal '97.71' type(double) = new total '-5.2300000000009'
37 The current total '-5.2300000000009' (double) + new subTotal '50' type(double) = new total '44.769999999999'

The code used to generate the above out put is:

Code: Select all

echo ($counter++) . " The current total '$transTotal' (".gettype($transTotal).") + new subTotal '$varTotal' type(".gettype($varTotal).") = new total '" . ($transTotal + $varTotal) ."'<br />";

Can any one offer an explanation as to where the "00000000009" is suddenly coming from?

Thanks
Glen

MeroD
New php-forum User
New php-forum User
Posts: 53
Joined: Wed Oct 10, 2012 12:14 am

Re: PHP returns incorrect total

Postby MeroD » Wed Nov 07, 2012 10:51 pm

Floating-point data types like DOUBLE are approximate and do not represent exact numbers.

number_format($...total) may give you better results.

ITI
New php-forum User
New php-forum User
Posts: 2
Joined: Wed Nov 07, 2012 8:28 am

Re: PHP returns incorrect total

Postby ITI » Thu Nov 08, 2012 6:29 am

MeroD wrote:Floating-point data types like DOUBLE are approximate and do not represent exact numbers.

number_format($...total) may give you better results.


I think one could argue that there is nothing approximate about "-102.94" and "97.71" and therefore the math should be performed correctly.

Using number_format() is no different than using round() without returning it as a string.

I have solved the problem by multiplying the input data by 100 and dividing the totals by 100 at the end to display the correct results.

What's interesting is that multiplying by 1 or by 10 does not correct it. It would seem it has something to do with the 2 decimals and by multiplying by 100 the values are now whole numbers (integers).

Thank you for the reply but I think there must be a better explanation.

Glen

johnj
php-forum Super User
php-forum Super User
Posts: 1805
Joined: Thu Mar 10, 2011 5:07 pm

Re: PHP returns incorrect total

Postby johnj » Thu Nov 08, 2012 8:23 am

It is better to use the bcmath function for math calculations.
http://php.net/manual/en/book.bc.php


Return to “PHP coding => General”

Who is online

Users browsing this forum: Baidu [Spider], Exabot [Bot] and 4 guests