note 78683 added to ref.simplexml
| From: | lordi at msdi dot ca | Date: | Tue, 23 Oct 2007 12:35:38 +0000 |
| Subject: | note 78683 added to ref.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131657@lists.php.net to get a copy of this message | ||
If you need to do math calculations on values extracted from simplexml document, you might need to
cast the value as float to prevent precision loss. Here is an example:
<?
$objXML = new SimpleXMLElement('<test x="-123.45"></test>');
//Shows correctly
echo $objXML['x']."\n";
//We loose the decimals
echo $objXML['x'] + $objXML['x']."\n";
$x = $objXML['x'];
//This works if we cast the amounts
echo (float)$objXML['x'] + (float)$objXML['x']."\n";
//Calculated on a string, no problem
echo "-123.45" + "-123.45";
?>
This is due to the fact that $objXML['x'] is not a string (php would cast it
automatically) neither a float, but a SimpleXMLElement object.
"echo var_dump($x);" will output this
~~
object(SimpleXMLElement)#3 (1) {
[0]=>
string(7) "-123.45"
}
~~
I opened a bug request on php but here is the answer they gave me:
~~
Status: Won't fix
The behavior is defined by the engine not the extension. When performing mathematical operations on
objects, they are treated as integers. It is up to the user to cast the object to the appropriate
type to maintain proper precision.
~~
----
Server IP: 216.235.15.211
Probable Submitter: 70.83.251.43
----
Manual Page -- http://www.php.net/manual/en/ref.simplexml.php
Edit -- https://master.php.net/note/edit/78683
Del: integrated -- https://master.php.net/note/delete/78683/integrated
Del: useless -- https://master.php.net/note/delete/78683/useless
Del: bad code -- https://master.php.net/note/delete/78683/bad+code
Del: spam -- https://master.php.net/note/delete/78683/spam
Del: non-english -- https://master.php.net/note/delete/78683/non-english
Del: in docs -- https://master.php.net/note/delete/78683/in+docs
Del: other reasons-- https://master.php.net/note/delete/78683
Reject -- https://master.php.net/note/reject/78683
Search -- https://master.php.net/manage/user-notes.php