note 78683 modified in ref.simplexml by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:18:11 +0000 |
| Subject: | note 78683 modified in ref.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155511@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:
<?php
$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.
~~
--was--
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.
~~
http://php.net/manual/en/ref.simplexml.php