2011-09-06 157 views
1

我有一個數字存儲在mysql中,類型爲float。從我讀過的,我應該能夠通過使用floor()來轉換float,但嘗試這個或其他任何操作都不起作用。希望有人能夠發現我做錯了什麼?如何將浮點數轉換爲整數?

例..

的數據庫顯示的價格爲$ 25.00 - 在我的PHP頁面,我有以下代碼(價格行轉換爲$價格後):

$price2 = floor($price); 
echo $price; 
echo '<br>'; 
echo $price2; 

我的結果是印刷:

$25.00 
0 

我也試着用'圓'代替'地板'。同樣的結果。

+2

你期待什麼?你的地板是''''。 –

回答

6

那是因爲你正在使用$25.00作爲輸入和$使得PHP認爲你想圓一個字符串 - PHP將圓一個(非數字)串0

  • floor =向下。
  • ceil =取整。
  • round =他們教你文法學校

但如果你有字符串中$無那些將工作同樣的過程。我建議你做一些類似'$' . round(str_replace('$', '', $price) * 100)/100的事情。 (乘法和除法使它四捨五入到最接近的一分錢(而不是美元),str_replace使它處理一個數字值,然後加上$。如果你真的很喜歡,那麼按照下面)

$dollar = '$' . round(str_replace('$', '', $price) * 100)/100; 
// the following makes sure that there are two places to the right of the decimal 
$pieces = explode('.', $dollar); 
if(isset($pieces[1]) && strlen($pieces[1]) == 1) 
{ 
    $pieces[1].='0'; 
    $dollar = implode('.', $pieces); 
} 
// if you like, you can also make it so that if !pieces[1] add the pennies in 
+0

打我幾秒鐘。 – canadiancreed

+2

呃,當把一個字符串強制轉換爲一個數字時,前面的'$'會導致轉換返回0,這樣會更準確。只要字符串可以轉換爲數。 – cdhowie

+0

謝謝!對不起,這個愚蠢的錯誤。很好的解釋!我應該說,數據庫顯示的價值爲25.00(不是25.00美元),所以我沒有意識到在這個代碼上面加上$符號 – Andi

0

正如cwallenpoole所說,你不能捨入一個非數字值。但是,你可以用數字來代替,例如

$price = '$25.25'; 
echo sprintf('$%0.2f', floor(preg_replace('/[^\d\.]/', null, $price)));