转换对象" 0.88923"到整数。我总是零

时间:2017-11-04 10:26:01

标签: php string object

我正在从XML Feed中检索一个对象,其值为" 0.88923"。我需要使用这个"数字"进行计算,但无论我尝试什么:

$rate = $nodes[0]['rate']; //(Get the "number" in this case 0.88923)

//Try to convert string (object) to integer, have tried all of these....
$rate = floatval($rate); //Yields 0
$rate = number_format($rate); //Yields 0
$rate = floatval($rate); //Yields 0

我可以实现整数,但总是为零。最令人沮丧的!

更新:var_dump给了我:

  

object(SimpleXMLElement)#7(1){[0] => string(7)" 0.88923" }

我的确切代码(目前使用下面的建议)是:

 $xref  = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
 $nodes = $xref->xpath('//*[@currency="GBP"]');

 //Current best suggestion below, but still not working
 $rate = floatval(strip_tags($nodes[0]['rate']->asXML()));

 if (ctype_digit($rate)) {
   echo "The string $rate consists of all digits.\n";
 } else {
   echo "The string $rate does not consist of all digits.\n";
 }  

 $calc = 1/$rate;

 echo $calc; //Should be about 1.13

2 个答案:

答案 0 :(得分:1)

您可以在费率上使用__toString()来获取字符串内容,然后通过floatval()将其转换为浮点数(不是问题中最初编写的整数):

<?php
$xref  = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
$nodes = $xref->xpath('//*[@currency="GBP"]');

// get contents as string, then convert to float:
$rate = floatval($nodes[0]['rate']->__toString());

$calc = 1/$rate;

echo $calc; //Should be about 1.13

答案 1 :(得分:0)

尝试使用round($rate);它应该正确圆! 这是一个例子:https://www.w3schools.com/php/showphp.asp?filename=demo_func_math_round