Mysql calculation issues: 1+1=1.999999999

£可爱£侵袭症+ 提交于 2019-12-03 16:15:44

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format

You can format numbers this way if thats what your after?

Adding 1 and 1 as floats or doubles should not result in anything but 2.

I find it hard to believe that 0.5 + 1.5 comes out to anything but 2.

All these numbers can be represented correctly in binary floating point.

I hate to say I don't believe your examples, but I don't. :-)

However, I do believe that you might have trouble with a number such as 1.1.

Why? Because 1/10 turns out to be a repeating decimal in binary.

The problem comes when trying to convert floating point numbers between decimal and binary representations. Some numbers make the trip fine, but others are only approximated.


However, if your examples really work like that, I have no idea what is happening, and I'd love to know.

floating point numbers are ALWAYS mere approximations. :-) If precision matters, figure out a way to use integers.

In my experience, when I used decimal datatype instead of float/double, I did always got the precise results.

This article explains the issue pretty well.

In a nutshell, very large, or very small floating point numbers can result in a loss of precision during calculations.

Don't expect integers when you work with floating point types.

Not sure if you're looking for an explanation or a solution, but since you've already gotten pointers to good explanations....

If you need your numbers to behave like integers, use integers. If you need a finite degree of precision (ie, two decimal places, for fields that represent money), store it as an integer anyway, but multiply it by whatever factor of 10 you need to get rid of the decimal when you put it into the database and divide by the same when you pull it back out.

So if you're representing a widget that costs $3.99, you put 399 into the WIDGET.cost field.

Dunno if that applies to your situation or not. But the general rule of thumb is that floating point numbers are ALWAYS mere approximations. :-) If precision matters, figure out a way to use integers.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!