I want to perform a very simple calculation with PHP, however, I get the wrong resuls.
My calculation: 20.66 * 1.21
(= approx. 25), PHP gives: 24.20
. I changed the 1.21
to 2
, that gives 40
... So PHP is telling me that 20.66 x 2 = 40
. When I just echo $resultaat
it gives the right value of 20.66
. (I get the 20.66
value out of an XML file)
I searched for "wrong PHP calculations" here and elsewhere but could not found similar errors. Any ideas?
My code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://URL');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '25');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($content);
$resultaat = $xml->Balance;
$resultaat2 = $resultaat * 1.21;
$resultaat3 = round($resultaat2, 2);
echo $resultaat3;
$xml->Balance returns a SimpleXmlElement. cast it to a double. change this line
$resultaat = $xml->Balance;
to this
$resultaat = (double)$xml->Balance;
$resultaat is a SimpleXMLElement not a string or a number. It seems that the type juggling of that class returns an integer value. if you cast the type to double it will work. Here is an example.
<?php
$xml = "<xml><value>20.66</value></xml>";
$xmlObj = simplexml_load_string($xml);
var_dump($xmlObj->value); //shows the type
var_dump($xmlObj->value * 2); // 40
var_dump((double)$xmlObj->value * 2); //41.32
I hope this will help.