2

I try to compare float value but I can't do it, I use this code:

float a = [[array objectAtIndex:(i+1)] floatValue];
float b = [[array objectAtIndex:(i)] floatValue];

a = [[NSString stringWithFormat:@"%.2f",a] floatValue];
b = [[NSString stringWithFormat:@"%.2f",b] floatValue];
step = [[NSString stringWithFormat:@"%.2f",step] floatValue];

float newStep = a-b;

if (newStep != step) {
      NSLog(@"NewStep: %f Step: %f",newStep,step);
}

this is the output:

2013-04-28 19:07:57.396 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 2.420000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000

obviously don't work, where is the mistake? the code seems to be correct!

3
  • 3
    Where do you assign to step for the first time? Also, the easier (and possibly working) comparison would be abs(a - b - step) < 0.005. Commented Apr 28, 2013 at 17:13
  • Try Googling around for "comparing floating point numbers"; there are lots of tricky bits. Commented Apr 28, 2013 at 17:19
  • step is a parameter, however thank you! I use this comparison and now it work! Commented Apr 28, 2013 at 17:29

1 Answer 1

4

Never ever compare float variables for equality! Floats are an approximation only, due to the limited accuracy. Use

if (fabs(a-b)<0.0001) {...

or something similar, if you want to check for equality.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.