Reputation: 965
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.
Upvotes: 4
Views: 1063
Reputation: 1476
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>
Upvotes: 1
Reputation: 4775
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
Upvotes: 1