[英]Drop Down of float values not showing option as selected
我正在顯示高度的下降,它包含浮點值。 當我在編輯表單上顯示此下拉菜單時,未顯示在其中選擇的舊高度值。
我想顯示下拉菜單中選擇的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>
有誰知道解決這個問題的方法嗎? 請幫忙。
正如Mark在評論中所說,這是一個浮點精度問題。 您可以通過在$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數學精度-NullUserException
在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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.