Reputation: 579
I get some rewards from a XMl and want to calculate the sum. Why isn't the output for $M_commission
166.63?
$i = 0;
$commission_trans = 0;
foreach($responseXml->lead as $lead)
{
if ($i == 0) {
$last_trans = $lead->leadTime;
}
$commission_trans = $commission_trans + $lead->reward;
echo $lead->reward;
echo "\n";
$i++;
}
$M_lastclick = $last_trans;
$M_commission = number_format($commission_trans, 2);
echo $M_commission;
echo "\n";
echo $M_lastclick;
Output: 100.0 0.63 3.0 30.0 3.0 30.0 166.00 2013-05-10T13:42:01.058+02:00
I tried
$commission_trans = number_format($commission_trans + $lead->reward, 2);
but same output.
Tnx a lot!
Upvotes: 3
Views: 106
Reputation: 5744
I think flag $first
is better than $i++
.
$first = true;
$commission_trans = 0.0;
foreach($responseXml->lead as $lead) {
if ($first) {
$last_trans = (float)$lead->leadTime;
$first = false;
}
$commission_trans += (float)$lead->reward;
echo $lead->reward.PHP_EOL;
}
$M_lastclick = $last_trans;
$M_commission = number_format($commission_trans, 2);
echo $M_commission.PHP_EOL;
echo $M_lastclick;
Test on Ideone: http://ideone.com/1pi7mQ
Upvotes: 1
Reputation: 11096
The "XML" indicates, this is coming from some XML stream (simple_xml?):
foreach($responseXml->lead as $lead)
and thus, the object members ($lead->reward
) are Strings, not Floats.
The $commission_trans
is initialized with a plain zero, so its an integer.
This line $commission_trans = $commission_trans + $lead->reward;
gives:
(int) = (int) + (string);
I would try to explicitly convert the XML string to a float:
$i = 0;
$commission_trans = 0.0;
foreach($responseXml->lead as $lead)
{
if ($i == 0) {
$last_trans = $lead->leadTime;
}
$commission_trans += floatval($lead->reward);
// or (float)$lead->reward;
echo $lead->reward;
echo "\n";
$i++;
}
Upvotes: 1