1

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!

Jack
  • 9,615
  • 18
  • 72
  • 112
  • 5
    It isn't a rounding issue, its off by thousands – Hanky Panky Nov 11 '13 at 14:48
  • 2
    I'd guess it's a locale issue - the thousands - separator – Hulk Nov 11 '13 at 14:49
  • @Hanky웃Panky - pah. This is what I get for commenting before the caffeine has a chance to hit. – andrewsi Nov 11 '13 at 14:49
  • 1
    Would the downvoter care to explain? The solution may be trivial, but I don't see any problem with the question itself. Code and output have been provided, and clearly the author has demonstrated effort? – Hulk Nov 11 '13 at 14:56

2 Answers2

5

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.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
Raphaël Malié
  • 3,912
  • 21
  • 37
  • 1
    You should use `DECIMAL` fields instead of `FLOAT` fields. More detail explanation is [here](http://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount) – Andy Nov 11 '13 at 15:03
2

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); ?>
John Skoumbourdis
  • 3,041
  • 28
  • 34