duandong1869 2018-07-05 13:42
浏览 81
已采纳

为什么PHP认为3.57 + 0.01等于3.5799999999999996? [重复]

This question already has an answer here:

Somehow PHP thinks that 3.57 + 0.01 equals 3.5799999999999996 in my script.

I tested about 10 other sums like this (e.g. 10.51 + 0.01) and then PHP gave me the correct answer (10.52 in the latter case). So, weirdly enough it only seems to make this mistake with these specific floats.

Code: (simplified for readability)

$users = array();

$IDs = [1,2,3];

foreach($IDs as $ID)
{
  $user = (object) array();
  $user->ID = $ID;
  $users[] = $user;
}

$initialAmount = 3.57;

$chosenIDs = [1,3];

foreach ($users as $key => $value)
{
  $users[$key]->amount = $initialAmount;
  if(in_array($key, $chosenIDs))
  {
    //the following returns 3.5799999999999996
    $users[$key]->amount = $users[$key]->amount + 0.01;

    //even if I do it like the following, it returns the wrong answer
    $users[$key]->amount = 3.57 + 0.01; //according to PHP equals 3.5799999999999996

    //the following actually gives the correct answer though
    //$users[$key]->amount = ($users[$key]->amount * 100 + 1) / 100;
  }
}

Is this some weird error in my configuration, or what is going on here?

</div>
  • 写回答

1条回答 默认 最新

  • dongshanni1611 2018-07-05 13:47
    关注

    As others have mentioned, it's a problem with Floating Point Math, not php.

    http://php.net/manual/en/language.types.float.php

    You can avoid it by using the BC Math extension when working with numbers where Floating Point errors would be a problem. It supports arbitrary precision.

    http://php.net/manual/en/ref.bc.php

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?