2013-09-27 70 views
4

我顯示下拉的高度和它的內容浮動值。當我在編輯表單上顯示這個下拉列表時,並沒有顯示在其中選擇的舊的高度值。下拉浮動值不顯示選項

我要顯示5.6英尺高度值作爲我的選擇降下來具有值4,4.1,4.2 .... 6.10,6.11,7等

以下是我用

代碼
<select name="height"> 
    <?php for($height=(4.0); $height <= 7; $height=($height+0.1)): ?> 
     <option value='<?php echo $height;?>' <?php if((5.6) == ($height)) echo "selected=selected"; ?> ><?php echo $height;?> ft</option> 
    <?php endfor;?>      
</select> 

是否有人知道這個問題的解決方案?請幫忙。

+5

浮點精度問題:'' –

+0

你也可以在這裏找到解決方案.. http://stackoverflow.com/questions/3148937/compare-floats-in-php&http://www.php.net/manual/en/language.types。 float.php –

回答

1

正如馬克在評論中所說,這是一個浮點精度問題。你可以在你的$height使用round()這樣解決這個問題:

<select name="height"> 
    <?php for($height=(4.0); $height <= 7; $height=($height+0.1)): ?> 
     <option value='<?php echo $height;?>' <?php if(5.6==round($height,2)) echo "selected=selected"; ?> ><?php echo $height;?> ft</option> 
    <?php endfor;?>      
</select> 

更多信息可以在這裏找到:A: PHP Math Precision - NullUserException

+0

謝謝傑米!它對我來說工作得很好。 –

+0

很高興能幫到你! –

1

浮動點PHP比較可以是一個相當痛苦。有解決的問題可能是做下面的比較,而不是5.6 == $height

abs(5.6-$height) < 0.1 

這將導致true 5.6和false有問題的其他值。

完整的解決方案:

<select name="height"> 
    <?php for($height=(4.0); $height <= 7; $height=($height+0.1)): ?> 
     <option value='<?php echo $height;?>' <?php if(abs(5.6-$height) < 0.1) echo "selected=selected"; ?> ><?php echo $height;?> ft</option> 
    <?php endfor;?>      
</select>