francesco.venica
francesco.venica

Reputation: 1721

Compare float value

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!

Upvotes: 2

Views: 1052

Answers (1)

Matthias
Matthias

Reputation: 8180

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.

Upvotes: 4

Related Questions