duanpi7107 2017-03-21 14:32
浏览 54
已采纳

0是1.87905246918E-14

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

  • 写回答

1条回答 默认 最新

  • doukou1718 2017-03-21 14:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办