Home > Software engineering >  php unexpected conversion to int
php unexpected conversion to int

Time:08-12

I have the following code excerpt

$sgn=$creditInvoice ? 1.0 : -1.0;
$net=$sgn*$s->totalNetValue;$vat=$sgn*$s->totalVatAmount;
 echo "net=$net vat=$vat s->totalNetValue=$s->totalNetValue s->totalVatAmount=$s->totalVatAmount gettype(s->totalNetValue)=".gettype($s->totalNetValue)."<br>";

The output is unexpectedly (to me)

net=-28 vat=-6 s->totalNetValue=28.32 s->totalVatAmount=6.80 gettype(s->totalNetValue)=object

The data has been read by simplexml_load_string so it has to do with that. If a cast the $s->totalNetValue to float or double it works correctly. What should I do to write "correct but not redundant code" ?

Bellow the complete code to reproduce:

<?php

$x='<?xml version="1.0" encoding="utf-8"?> <invoice> <invoiceSummary> <totalNetValue>20.12</totalNetValue> <totalVatAmount>4.83</totalVatAmount> </invoiceSummary> </invoice>';

$i = simplexml_load_string($x);

print_r($i);echo '<br>';

$s = $i->invoiceSummary;

print_r($s);echo '<br>';

$net=1.0*$s->totalNetValue;
$vat=1.0*$s->totalVatAmount;

echo "net=$net vat=$vat s->totalNetValue=$s->totalNetValue s->totalVatAmount=$s->totalVatAmount gettype(s->totalNetValue)=".gettype($s->totalNetValue)."<br>";

?>

CodePudding user response:

Okay, coffee finally kicked in an I'm seeing what everyone else was seeing.

Prior to PHP 7.3, when SimpleXML objects were used in a mathematical context they were always treated as ints. This change is documented here.

And you can see the old way here and the new way here

  • Related