PHP:变量是int但无法执行计算
$bal = (int)$balance;
echo is_int($bal);
$balance 来自 file_get_contents($webservice);
我正在使用 (int) 将字符串转换为整数。 is_int 返回 1 表示 true 作为验证。
因为 $bal 的值始终为负数,所以我进行以下计算以使其为正值:
$bal = $bal * -1;
当我这样做时,该值将变为 0,即使 $bal 之前可能为 -150。
编辑1 var_dump ($balance) 正在返回: 字符串(110)“ -399.6000"
编辑 2 我已经使用 XML 解析器将变量分配给数组 - 请参阅下面的答案。
$bal = (int)$balance;
echo is_int($bal);
$balance is from a file_get_contents($webservice);
I am using (int) to convert a string to integer. is_int returns 1 for true as verification.
Because the value of $bal is always negative, I do the following calculation to make it a positive:
$bal = $bal * -1;
When I do this, the value becomes 0 even though $bal may be -150 previously.
EDIT 1
var_dump ($balance) is returning:
string(110) "
-399.6000"
EDIT 2 I have used XML Parser to assign variable to array - see my answer below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果你想确保你总是处理正数:
I recommend PHP's
abs()
-function if you want to make sure that you are always dealing with a positive number:根据您的
var_dump
输出,您的字符串以空格开头。使用:$bal = intval(trim($balance));
As per your
var_dump
output, your string begins with a space. Use this:$bal = intval(trim($balance));
问题是我使用 file_get_contents 与 Web 服务的 GET 方法进行交互。
这是返回 XML 头数据,我在分配给变量时忽略了它。
为了清除 XML 只留下我想要的值,我使用了 PHP XML_PARSER,它将 file_get_contents 存储到一个数组中,并允许我将数组值分配给一个整数。
The issue is that I was using file_get_contents to interact with a GET method for a Web Service.
This was returning XML header data which I overlooked when assigning to a variable.
To clear out the XML to leave me with just the value I wanted, I used the PHP XML_PARSER which stored file_get_contents into an array and allowed me to assign the array value to an integer.
如果您想恢复符号,请尝试此操作:
或使用 abs() 如果你希望它始终为正:
try this to if you want to revert the sign:
or use abs() if you want it to be always positive:
http://php.net/manual/en/function.abs.php
http://php.net/manual/en/function.abs.php
给出-150
gives -150
执行乘法后,程序对 $bal 执行什么操作?以下 PHP 脚本在我的笔记本电脑上按预期工作:
输出为“1150”,因为我没有考虑换行符。你能发布更多你的代码吗
What is your program doing with $bal after you do the multiply? The following PHP script worked as expected on my laptop:
Output is "1150" because I didn't bother with linebreaks. Can you post any more of your code
我认为您可以通过使用函数 intval() 来简化计算,该函数返回任何变量的整数值。如果您有 php 手册,请仔细阅读函数说明。
I think you can make your calculations easy by using the function intval() which returns the integer value of any variable. Go through the function description if you have a php manual.