doze79040 2019-07-07 19:05
浏览 97
已采纳

PHP如果for循环中的条件具有浮点数[duplicate]

This question already has an answer here:

An if condition in a for loop would stop working after (n) times.

I'm using PHP 7.3.6-1+ubuntu18.04.1+deb.sury.org+1

Given the following code:

for($i = 0.99; $i<= 30.99; $i++){
    echo $i;
    if($i == 10.99){
        echo '<--- selected';
    }
    echo '<br>';
}

output

0.99
1.99
2.99
3.99
4.99
5.99
6.99
7.99
8.99
9.99
10.99<--- selected
11.99
12.99
13.99
14.99
15.99
16.99
17.99
18.99
19.99
20.99
21.99
22.99
23.99
24.99
25.99
26.99
27.99
28.99
29.99

This remain true when the condition is between 0.99 - 15.99, However, changing the condition between 16.99 - 29.99, <--- selected is not returned.

I ran few tests using int in my loop as shown below and it seems to work fine.

for($i = 0; $i<= 30; $i++){
    echo $i;
    if($i == 18){
        echo '<--- selected';
    }
    echo '<br>';
}

I think the problem is related to this float (0.99 - 30.99).

</div>
  • 写回答

2条回答 默认 最新

  • drh37116 2019-07-07 19:14
    关注

    A possible solution is to make the numbers string and that way compare them.
    Using "10.99" on one side and number_format on the other

    for($i = 0.99; $i<= 30.99; $i++){
        echo $i;
        if(number_format($i,2) == "22.99"){
            echo '<--- selected';
        }
        echo "
    ";
    }
    

    https://3v4l.org/mvOR3

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题