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?

8
  • Have you tried casting the numbers as floats? This may help stackoverflow.com/questions/481466/php-string-to-float Commented Oct 5, 2016 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. Commented Oct 5, 2016 at 16:04
  • @aynber That shouldn't matter. PHP does all arithmetic as floats. Commented Oct 5, 2016 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? Commented Oct 5, 2016 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... Commented Oct 5, 2016 at 16:11

1 Answer 1

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 />";
Sign up to request clarification or add additional context in comments.

1 Comment

This shouldn't be necessary. It works without using the cast. ideone.com/7iu2bI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.