我有两个值:
$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
总是浮点数,那么你可以做数学......?
所以我的问题:
$currentValue = string(8) "2,061.14"
,我$newCurrentValue = (float)$currentValue
,$newCurrentValue = string(1) "2"
。不知道那里发生了什么?$usersValue = string(2) "52"
,我如何将其转换为$usersValue = float(52.00)
?<
和>
运算符有效,但不是==
...?真的很困惑,谢谢。
答案 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;
你的问题是你的值中有一个“,”浮点数只能包含数字和一个点