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 报酬10000,做一个简单的换汇网站
  • ¥15 关于#vue.js#的问题:word excel和ppt预览问题语言-javascript)
  • ¥15 Apache显示系统错误3该如何解决?
  • ¥30 uniapp小程序苹果手机加载gif图片不显示动效?
  • ¥20 js怎么实现跨域问题
  • ¥15 C++dll二次开发,C#调用
  • ¥15 请教,如何使用C#加载本地摄像头进行逐帧推流
  • ¥15 Python easyocr无法顺利执行,如何解决?
  • ¥15 为什么会突然npm err!啊
  • ¥15 java服务连接es读取列表数据,服务连接本地es获取数据时的速度很快,但是换成远端的es就会非常慢,这是为什么呢