PHP:数字/类型转换的问题

时间:2013-10-03 16:14:21

标签: php operators

我有两个值:

$currentValue将始终有两位小数(可以是.00)。

$usersValue可以是整数,也可以是小数到两位小数。

我遇到的问题是这些都是字符串(例子):

var_dump($currentValue) = string(6) "100.50"
var_dump($usersValue) = string(5) "52.50" || string(2) "52"

现在我需要对这些做一些逻辑:

if($usersValue > $currentValue) // Is users value greater than the current value
if($usersValue < $currentValue) // Is users value less than the current value
if($usersValue == $currentValue) // Is the users value equal to the current value

在我看来,我认为这两个变量应该总是被声明为浮点数,因为$currentValue总是浮点数,那么你可以做数学......?

所以我的问题:

  1. 如何将字符串正确转换为浮点数?例如:如果我的$currentValue = string(8) "2,061.14",我$newCurrentValue = (float)$currentValue$newCurrentValue = string(1) "2"。不知道那里发生了什么?
  2. 如果$usersValue = string(2) "52",我如何将其转换为$usersValue = float(52.00)
  3. 如果所有变量都是浮点数,我能否按上述方法执行我需要的逻辑?根据我的测试,我发现<>运算符有效,但不是== ...?
  4. 真的很困惑,谢谢。

2 个答案:

答案 0 :(得分:2)

要将字符串转换为float,请使用floatval()函数。

对于$usersValue,您可以直接使用该功能:

$usersValue = floatval($usersValue);

$currentValue无法做到这一点。您需要先删除逗号:

$currentValue = str_replace(',', '', $currentValue);
$currentValue = floatval($currentValue);

现在,由于两个数字都属于同一类型,因此您的比较应该有效:

echo ($usersValue > $currentValue) ? '$usersValue greater' : '$currentValue greater';
echo ($usersValue < $currentValue) ? '$currentValue greater' : '$usersValue greater';
echo ($usersValue == $currentValue) ? 'equal' : 'not equal';

输出:

$currentValue greater
$currentValue greater
not equal

答案 1 :(得分:0)

就这样做:

$currentValue = (float)$currentValue;
$usersValue = (float)$usersValue;

你的问题是你的值中有一个“,”浮点数只能包含数字和一个点