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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程