3

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!

3
  • Please show $commission_trans value. Commented May 14, 2013 at 5:15
  • @CertaiN 166.00 , it is already there. Commented May 14, 2013 at 5:16
  • The expected output is 166.63 and not 166.00: 100.0 + 0.63 + 3.0 + 30.0 + 3.0 + 30.0 = 166.00 ?? - so its not working like above since there are some type caveats with xml strings as summands. Commented May 14, 2013 at 5:24

2 Answers 2

1

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

1 Comment

@Axel Amthor removed mine. There is someone else.
1

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

Comments

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.