简体   繁体   English

PHP:变量为int但无法执行计算

[英]PHP: Variable is int but can't perform calculation

$bal = (int)$balance;
echo is_int($bal);

$balance is from a file_get_contents($webservice); $ balance来自file_get_contents($ webservice);

I am using (int) to convert a string to integer. 我正在使用(int)将字符串转换为整数。 is_int returns 1 for true as verification. is_int返回1作为true作为验证。

Because the value of $bal is always negative, I do the following calculation to make it a positive: 由于$ bal的值始终为负,因此我进行了以下计算以使其为正:

$bal = $bal * -1;

When I do this, the value becomes 0 even though $bal may be -150 previously. 当我这样做时,即使$ bal以前可能是-150,该值也变为0。

EDIT 1 var_dump ($balance) is returning: string(110) " -399.6000" 编辑1 var_dump($ balance)返回:字符串(110)“ -399.6000”

EDIT 2 I have used XML Parser to assign variable to array - see my answer below. 编辑2我已经使用XML解析器将变量分配给数组-请参阅下面的答案。

如果您要确保始终使用正数,建议使用PHP的abs() -函数

$bal = abs($bal);

As per your var_dump output, your string begins with a space. 根据您的var_dump输出,您的字符串以空格开头。 Use this: 用这个:

$bal = intval(trim($balance));

The issue is that I was using file_get_contents to interact with a GET method for a Web Service. 问题是我正在使用file_get_contents与Web服务的GET方法进行交互。

This was returning XML header data which I overlooked when assigning to a variable. 这是返回XML头数据,在分配给变量时我忽略了它。

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. 为了清除XML,让我只剩下想要的值,我使用了PHP XML_PARSER,该文件将file_get_contents存储到数组中,并允许我将数组值分配为整数。

$result = file_get_contents($base);

$p = xml_parser_create();
xml_parse_into_struct($p, $result, $vals, $index);
xml_parser_free($p);  
$bal = $vals[0]['value'];
echo $bal *-1;

try this to if you want to revert the sign: 如果您想还原符号,请尝试以下操作:

$bal = $bal * (-1);

or use abs() if you want it to be always positive: 或使用abs()如果希望它始终为正:

$bal = abs($bal);
$balance="-150";
$bal = $balance*1;
echo $bal;

gives -150 给出-150

I think you can make your calculations easy by using the function intval() which returns the integer value of any variable. 我认为您可以使用函数intval()来简化计算,该函数返回任何变量的整数值。 Go through the function description if you have a php manual. 如果您有php手册,请仔细阅读功能说明。

What is your program doing with $bal after you do the multiply? 乘法后,程序用$ bal做什么? The following PHP script worked as expected on my laptop: 以下PHP脚本在笔记本电脑上可以正常工作:

<?php
$balance = "-150";
$bal = (int)$balance;
echo is_int($bal);
$bal = $bal * -1;
echo $bal;
?>

Output is "1150" because I didn't bother with linebreaks. 输出为“ 1150”,因为我没有打扰换行。 Can you post any more of your code 您还能发布更多代码吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM