dongzg2006 2013-09-28 00:26
浏览 41
已采纳

PHP / MYSQL的异常值浮动[重复]

This question already has an answer here:

I just hit an odd issue. I have the following tables in MySQL:

table:deposits
user_id    amount
1          0.50

table:withdrawls
user_id    amount
1          0.01
1          0.01
1          0.01

To get the balance, I run this:

SELECT (IFNULL((SELECT sum(amount) FROM deposits WHERE user_id = 1),0) - IFNULL((SELECT sum(amount) FROM withdrawls WHERE user_id = 1),0) ) as balance

I then return it as

return (float) $row['balance']

For some weird reason, the result is float(0.47000000067055). Does anyone know why there is bizarre rounding?

</div>
  • 写回答

1条回答 默认 最新

  • duanchi8836 2013-09-28 00:54
    关注

    Floating-point arithmetic does not represent all real numbers exactly. 0.01 is converted to a representable value, which is, in essence, a binary numeral with a limited number of significant bits. Since 1/100 cannot be represented exactly in binary with a finite number of digits (the same way 1/3 in decimal requires an infinite number of digits: .3333…), the conversion to floating-point rounds the value.

    That said, I do not see exactly how 0.47000000067055 is produced. Converting 0.01 to IEEE-754 64-bit binary floating-point with correct rounding to nearest produces 0.01000000000000000020816681711721685132943093776702880859375. Subtracting that three times from .5, rounding each time, produces 0.4699999999999999733546474089962430298328399658203125. Subtracting three times the value from .5 produces the same value.

    I suspect that your PHP implementation converted 0.01 to floating-point in a less than optimal way.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器