Jack
Jack

Reputation: 9784

PHP is calculating simple addition incorrectly...?

This is the output I am seeing from my PHP script:

Cash Completions (Purchase)
Product A: £435.60
Product B: £38.40
Product C: £0.00
Product D: £3,349.87
Product E: £559.38
Product F: £0.00
Product G: £0.00
Product H: £0.00
TOTAL COSTS: £1,036.38

Take a look at the last line, "TOTAL COSTS". You will see it doesn't add up to the total of all the rows above.

Here is the PHP script used to calculate this:

Cash Completions (Purchase)
Product A:  <?php echo '£'.$extra->a;?>
Product B:  <?php echo '£'.$extra->b;?>
Product C:  <?php echo '£'.$extra->c;?>
Product D:  <?php echo '£'.$extra->d;?>
Product E:  <?php echo '£'.$extra->e;?>
Product F:  <?php echo '£'.$extra->f;?>
Product G:  <?php echo '£'.$extra->g;?>
Product H:  <?php echo '£'.$extra->h;?>
TOTAL COSTS: <?php echo '£'.number_format($extra->a + $extra->b + $extra->c + $extra->d + $extra->e + $extra->f + $extra->g + $extra->h, 2);?>

The $extra variable is an object representing a MySQL Resultset. As you can see, the output of the individual products is correct, but for some reason the total is miles off.

Any ideas?

Thanks!

Upvotes: 2

Views: 144

Answers (2)

John Skoubourdis
John Skoubourdis

Reputation: 3259

The problem is with the number:

3,349.87

It should be instead:

3349.87

The number 3,349.87 is not a correct number for PHP. PHP only recognize and translate the dot ('.') and not the comma (',')

You could simply do:

$total = (float)str_replace(",","",$extra->a) + (float)str_replace(",","",$extra->b) + ...

TOTAL COSTS: <?php echo '£'.number_format($total, 2); ?>

Upvotes: 2

Rapha&#235;l Mali&#233;
Rapha&#235;l Mali&#233;

Reputation: 4012

3,349.87 price in product D is not a valid PHP number, it's the reason why your addition fails. Normalize your prices in database, use float fields.

Upvotes: 4

Related Questions