|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2007-09-27 16:51 UTC] lordi at msdi dot ca
Description:
------------
Calculations on values got from a simplexml object dont work as expected.
String values looking as float seems to be casted as integers
Reproduce code:
---------------
<?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";
//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";
?>
Expected result:
----------------
-123.45
-246.9
-246.9
-246.9
Actual result:
--------------
-123.45
-246
-246.9
-246.9
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Nov 04 23:00:01 2025 UTC |
Hi, I was about to report this bug myself, and am surprised at the resolution, as this seems to be very unhelpful and unexpected behaviour. Consider the following minimal test case: <?php $x = simplexml_load_string('<x>2.5</x>'); var_dump($x*1); // int(2) var_dump((string)$x*1) // float(2.5) ?> Is there any other value of $x that would create the behaviour shown with those 2 var_dump() calls? You say that "when performing mathematical operations on objects, they are treated as integers", but I'm not aware of any other object which interprets its contents to cast to integer in this way. Certainly any user-defined class will simply become int(1) in this context, so SimpleXML is *attempting* to perform extra "magical" functionality here. I discovered this in a production application which was dropping pennies from prices returned in XML by a supplier - a non-trivial bug. If the implicit cast had resulted in int(1), like any other object, this would have been ridiculously obvious; but since SimpleXML('<x>42.0</x>') appears to act as float(42.0), there was no reason to suspect that SimpleXML('<x>42.5</x>') would not act as float(42.5). I also note that if $x in the example were the string '2.5', var_dump($x*1) would result in float(2.5) as expected, so it is not true that the engine has already decided that the variable is in int context. If this is a limitation of the engine, then that should be raised as a dependency of fixing this bug, not used as an excuse to dismiss it. Many thanks for all your efforts, Rowan Collins