我有一个foreach循环,输出一堆数字,然后我想取所有这些数字并将它们加在一起。但是,当我这样做时,它只会在小数点之前加起来。我觉得也许我错过了number_format的东西?
以下是代码:
$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 />";
这显示以下内容:
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
有什么想法吗?
答案 0 :(得分:0)
@craig得到了这个!
解决方案是将其更改为以下内容:
$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 />";