doucheng5209 2013-02-24 04:55
浏览 40
已采纳

PHP有一个比较分裂后的bug

I have a problem with PHP comparing after I divide a value float and integer.

Here my code :

<?php

    function test_promo($price) {
        $tmpprice = $price*100;
        $divprice = $tmpprice/intval($tmpprice);
        if ( $divprice > 1 ) {
            echo "$price = TRUE
";
            //TODO do something >1
        }
        else {
            echo "$price = FALSE
";
            //TODO do something <=1
        }
    }

    echo "<pre>";
    test_promo(2.41);   //output--> 2.41 = FALSE
    test_promo(2.42);   //output--> 2.42 = FALSE
    test_promo(2.43);   //output--> 2.43 = TRUE
    test_promo(2.44);   //output--> 2.44 = FALSE
    test_promo(2.45);   //output--> 2.45 = TRUE
    test_promo(2.46);   //output--> 2.46 = FALSE
    test_promo(2.47);   //output--> 2.47 = TRUE
    test_promo(2.48);   //output--> 2.48 = FALSE
    test_promo(2.49);   //output--> 2.49 = TRUE
    echo "</pre>";

?>

As you can see the result must be all FALSE but it's not :S

Is it a bug in PHP or just only my computer (Ubuntu x64) has this bug?

SOLUTION :

As the corrected answer below, I need to get only float number as define (the number after .) like this $divprice = number_format( $newprice/intval($newprice), 2 );

  • 写回答

3条回答 默认 最新

  • dounie0889 2013-02-24 05:03
    关注

    Floating points can not represent exactly the value you posted in decimal. In other words, 2.43 is not really 2.43, but actually [something close to] 2.4300000000000003. So when you divide 243.00000000000003 by 243 the result will be greater than 1.

    This is not a bug in PHP, just the way floating point works (in any language). If you need to work with exact decimal values, you'd better search for a specific library to do that. This question might be a good starting point.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c