[英]Drop Down of float values not showing option as selected
I am displaying a drop down of height and it content float values. 我正在显示高度的下降,它包含浮点值。 When I displaying this drop down on edit form, not showing old value of height as selected in it.
当我在编辑表单上显示此下拉菜单时,未显示在其中选择的旧高度值。
I want to show 5.6 ft height value as selected in my drop down having values from 4, 4.1, 4.2....6.10, 6.11, 7 etc. 我想显示下拉菜单中选择的5.6英尺高度值,该值的取值为4、4.1、4.2 .... 6.10、6.11、7等。
Following is the code that I used 以下是我使用的代码
<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>
Is any one know solution to this issue ? 有谁知道解决这个问题的方法吗? Please help.
请帮忙。
As Mark said in his comment, this is a floating point precision issue. 正如Mark在评论中所说,这是一个浮点精度问题。 You can solve this by using
round()
on your $height
like this: 您可以通过在
$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>
More information can be found here: A: PHP Math Precision - NullUserException 在这里可以找到更多信息: A:PHP数学精度-NullUserException
Comparing floating points in PHP can be quite a pain. 在PHP中比较浮点可能会很麻烦。 A solution to the issue could be to do the following comparison instead of
5.6 == $height
: 解决该问题的方法可能是执行以下比较,而不是
5.6 == $height
:
abs(5.6-$height) < 0.1
This will result in true
for 5.6 and false
for the other values in question. 这将导致
true
为5.6和false
对有问题的其他值。
Full solution: 完整解决方案:
<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.