php - Multiplying number from XML gets rounded -
i pulling exchange rate yahoo's xml (euros dollars) think need multiply rate dynamic value. however, rate pulling not multiplying correctly.
<?php $xml=simplexml_load_file("http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22eurusd%22%29&env=store://datatables.org/alltableswithkeys") or die(); foreach ($xml->results->rate $item){ $eur2usd = $item->rate; } echo $eur2usd*2; // gives me looks rounded number "2" echo 1.2475*2; // when put in rate hand (1.2475) multiplication works = "2.495" ?>
why simple math not working?
edit - adding xml
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="1" yahoo:created="2014-11-27t11:45:32z" yahoo:lang="en-us"> <results> <rate id="eurusd"> <name>eur usd</name> <rate>1.2482</rate> <date>11/27/2014</date> <time>6:44am</time> <ask>1.2483</ask> <bid>1.2481</bid> </rate> </results> </query>
you've run type-juggling anomaly. php sees you're trying multiply string , attempts cast type can multiplied. in infinite wisdom, reason casting string integer.
you should never rely on php's type juggling right thing because in rare cases when doesn't, produce unpredictable results. instead, should explicitly cast input data
$eur2usd = (float) $item->rate;
or
$eur2usd = floatval ($item->rate);
Comments
Post a Comment