-2

I am testing my code. I have boolean conditions with float numbers.

I assign a float value to test my code:

float testFloatValue = 0.9;

And the boolean condition is not met:

if (testFloatValue == 0.9) {

}

Because when I debugging, my float number has changed from 0.9 to 0.899999976

I do not understand anything!

David
  • 1
  • 2
  • 1
    http://floating-point-gui.de/ http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and many more. – Hot Licks Apr 07 '15 at 21:47
  • Not all numbers can be expressed fully in all bases. 0.9 (decimal base) can to be represented fully in base 2 in the same manner 1/3 can not be represented fully in decimal. Read up on floating point numbers. – zaph Apr 07 '15 at 21:49
  • possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Jim Lewis Apr 07 '15 at 22:05

2 Answers2

2

Due to the nature of floating point numbers certain values are not possible to be represented exactly. So you NEVER want to do a direct check for equality... there are numerous articles about this on the web and if you search you will find many. However here is a quick routine you can use in Objective C to check for ALMOST equal.

bool areAlmostEqual(double result, double expectedResult)
{
    return fabs(result - expectedResult) < .0000000001;
}

You would use it like so as per the values in your original question:

if(areAlmostEqual(testFloatValue, 0.9) {
    // Do something
}
Cliff Ribaudo
  • 8,932
  • 2
  • 55
  • 78
0

This is a very common misconception. A floating point number is an approximate representation of a real number. The most common standard for floating point (IEEE 754) uses base 2, and base 2 cannot directly represent all base 10 numbers.

This is nothing to do with Xcode When you wrote 0.9 which is 9 * 10^-1, the computer stored it as the closest binary equivalent, expressed in base 2. When this binary (base 2) approximation is converted back to decimal (base 10) for display, you get 0.899999976 which is as close as floating point could represent your number.

The standard way to compare floating point numbers is to choose a precision or tolerance, often called epsilon, which is how close two numbers are to be considered equal (ie. "close enough"). And because the closest approximation might be slightly lower or slightly higher than your number, you would take the absolute difference and compare to the tolerance. Thus:

const float eps = 0.00001f;
if (fabs(a - b) < eps)
{
    // a and b are approximately equal
}

Floating point is a large and complicated topic, and is definitely worth researching to get a good grasp. Start here:

You should definitely read this fantastic introduction to floating point:

gavinb
  • 19,278
  • 3
  • 45
  • 60