2017-10-08 31 views
0
$amount = (256.34 * 100); 
echo (int) ($dollor_amount); 

// out should be 25634 but this giving 25633, not sure why? 


$amount = (255.34 * 100); 
echo (int) ($dollor_amount); 
// For 255.34 it returning fine output 25534 

是否有任何限制的問題?它僅在256數字後表現出意外。浮動到int類型轉換25634到25633在php

+0

見[該SO主題](https://stackoverflow.com/questions/14082287/why-are-floating-point-numbers-printed-so-differently)。基本上,你永遠不能依靠100%的浮點數。這裏最可能的是'256.34 * 100''實際上是'256.33999999999999 * 100',所以你得到'25633.99999',並且當被指定爲int時,小數點就被切斷。 – Qirel

+1

我想知道的是爲什麼[當你不是將它轉換爲int](https://tio.run/##[email protected]/fxr4go4BLJTE3vzSvRMFWQcPI1EzP2ERBS8HQwEDTmis1OSNfASoN5SnFFMXkKUE5Gpl5JZoKGlAVmmhKUA02pchge7v//wE)時,它會打印預期結果。 – Ivar

+1

它與如何執行浮點算術(以及「(int)3.14'變爲'3」的事實無關,而與小數點的上整數有多接近)無法依賴。 [這是另一個線程](https://stackoverflow.com/questions/3726721/php-floating-number-precision)這可能是更多的信息。 – Qirel

回答

0

用float代替int。你會得到你想要的結果作爲你的問題。

$amount = (256.34 * 100); 
echo (float) ($amount); 

// out should be 25634 but this giving 25633, not sure why? 

$amount = (255.34 * 100); 
echo (float) ($amount); 
+0

在這種情況下,您也可以不使用它。 – Ivar

+0

如果我們沒有在int中轉換,爲什麼會拋出float來浮動 - ? –

+0

我需要int值 –