2013-10-03 47 views
0

我有兩個值:PHP:問題編號/型鑄造

$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. 如果所有的變量都是浮點數,我能夠按照上面所描述的來完成我需要的邏輯嗎?從我的測試中,我發現<>運營商工作,但不是== ...?

真的很困惑,謝謝。

+0

如果一個字符串包含數千個分隔符,如'2,061.14',那麼你需要在其他任何東西之前刪除它們(使用類似'$ value = str_replace(',','',$ value);' –

回答

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 
+0

非常感謝:) – Alias

+0

@Al ias:不客氣! –

0

就這樣做:

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

你的問題是,你有一個「」在你的價值,一個浮動只能包含數字和一個點