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 -- h
ttps://master.php.net/note/delete/78683/integrated
Del: useless -- http
s://master.php.net/note/delete/78683/useless
Del: bad code -- htt
ps://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 -- http
s://master.php.net/note/delete/78683/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78683
Reject -- https://mast
er.php.net/note/reject/78683
Search -- https://
master.php.net/manage/user-notes.php
--
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php
|