0

Why Subtraction of two equal values in mysql does not equal zero?

both field type are double. See image below enter image description here

Robbert
  • 6,481
  • 5
  • 35
  • 61
Md. Sahadat Hossain
  • 3,210
  • 4
  • 32
  • 55
  • 1
    those field are double. @MitchWheat – Md. Sahadat Hossain Jan 20 '14 at 05:17
  • 3
    Obligatory link: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html) – Ken White Jan 20 '14 at 05:21
  • 1
    Quantities should NOT be double. Make them integer – Mitch Wheat Jan 20 '14 at 05:35
  • @KenWhite, Obligatory upvote to obligatory link :). OP: TL;DR: You're going to have errors if you use floating point numbers, in this case the value is tiny, so it won't make much of a difference if you're using it in further arithmetic operations – Pranav Hosangadi Jan 20 '14 at 05:35

2 Answers2

3

That's known as a approximate precision . This isn't an error, floating point data types are intended to work such way. They can not store data precisely. So if that matters, you should use fixed-point data types, such as DECIMAL in MySQL.

On the other hand, you can always use precision delta for comparisons for floating point, like:

SELECT 
  `foo`,
  `bar`,
  IF(ABS(`foo`-`bar`)<1E-13, 0, `foo`-`bar`) AS zero_compared
FROM
 t

as you can see, here delta is 1E-13 (normally, that will be enough)

Alma Do
  • 37,009
  • 9
  • 76
  • 105
1

This problem is due to floating point precision and calculations on them. You can also refer this Issue for clarity on your problem:

MySQL floating point comparison issues

Community
  • 1
  • 1
Aman Aggarwal
  • 17,619
  • 9
  • 53
  • 81