0

For one of our projects we need a value input that supports number localization in IE, and as can be seen here (link) IE doesn't support comma separation. To work around this issue I figured to make a dropdown that has all values with commas.

I've run into a strange problem in automatically generating this range. It works for all values except 0. I hope there is a solution out there (or a logical explanation) to solve or help me understand this strange behaviour. The code I use:

$select_number = "";

for ($i = 10; $i >= 0; $i -= 0.1){
    $value = str_replace(".", ",", $i );
    $select_number .= "<option value='" . $value . "' $selected>" . $value . "</option>";
}

this code is placed in the interface with

<select class="form-control" id="myname" data-live-search="true" name="myname">
    <?php echo $select_number; ?>
</select>

This renders the the following dropdown

0 = 1,87905246918E-14

Notice that 0 became 1,87905246918E-14. If I change the order of the for loop to for($i = 0; $i <= 10: $i += 0.1) everything works fine... Anybody know a solution to this?

I use php version 5.6.28

Tom Groentjes
  • 1,053
  • 8
  • 7

1 Answers1

2

Loop through the integers instead:

$select_number = "";

for ($i = 100; $i >= 0; $i -= 1){
  $value = str_replace(".", ",", $i/10 );
    $select_number .= "<option value='" . $value . "' $selected>" . $value . "</option>";
}

Floating-point numbers suffer from round-off error.

Jack Valmadre
  • 888
  • 7
  • 23