0

I have a foreach loop that is outputting a bunch of numbers and then I want to take all of those numbers and add them together. However, when I do this, it only adds together whats before the decimal point. I feel like maybe I am missing something with number_format maybe??

Here is the code:

$totalHours = '0';
  foreach ($timeEntries as $entry) {
    $entryID = $entry->id;
    $entryHours = $entry->hours;
    $entryDate = $entry->spent_at;
    $totalHours += $entryHours;
    echo $entryHours."<br />";
  }
  echo "All added up: $totalHours <br />";

And that is displaying the following:

0.7
0.5
0.53
2.6
0.8
0.2
0.5
2.22
1.28
0.57
0.55
0.35
0.5
0.5
1.2
1.4
1.2
0.5
0.82
1.0
0.17
0.33
2.0
1.0
0.5
1.0
0.17
1.97
All added up: 14 

Any ideas?

Shawn Kemp
  • 21
  • 3
  • Have you tried casting the numbers as floats? This may help http://stackoverflow.com/questions/481466/php-string-to-float – Craig Oct 05 '16 at 16:00
  • `$totalHours` should be set to `0.0` (without the quotes), so it's cast as a float from the start, not an string-as-integer. – aynber Oct 05 '16 at 16:04
  • @aynber That shouldn't matter. PHP does all arithmetic as floats. – Barmar Oct 05 '16 at 16:08
  • What are the types of `$timeEntries`, `$entry` and `$entry->hours`? It seems like `$entry->hours` is not a string and also not a float... maybe an object that has float representation as a string? – Dekel Oct 05 '16 at 16:11
  • @Barmar You're correct. I was just testing it out. On the other hand, it's supposed to add up to more than 24, so there's something going on there... – aynber Oct 05 '16 at 16:11
  • Can you use `var_dump($entryHours)` instead of `echo`? – Dekel Oct 05 '16 at 16:12
  • I can't reproduce your problem. When I try it, it says they added up to 25.06. – Barmar Oct 05 '16 at 16:12
  • @craig that worked!! Thank you everyone for the help! I added the following $floatHours = (float) $entryHours; $totalHours += $floatHours; – Shawn Kemp Oct 05 '16 at 16:22

1 Answers1

0

@craig got this one!

Solution was to change it to the following:

  $totalHours = '0';
  foreach ($timeEntries as $entry) {
    $entryID = $entry->id;
    $entryHours = $entry->hours;
    $entryDate = $entry->spent_at;
    $floatHours = (float) $entryHours;
    $totalHours += $floatHours;
  }
  echo "All added up: $totalHours <br />";
Shawn Kemp
  • 21
  • 3