简体   繁体   中英

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.

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. You can solve this by using round() on your $height like this:

<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

Comparing floating points in PHP can be quite a pain. A solution to the issue could be to do the following comparison instead of 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM