3

Possible Duplicate:
CGFloat addition bug?

I have a CGPoint (which is just a struct around two CGFloats). Can someone explain to me how these two lines of code:

player.position = CGPointMake(player.position.x + 12.8f, player.position.y + 12.8f);
NSLog(@"%f,%f", player.position.x, player.position.y);

are generating this output:

828.799988,236.800003
841.599976,249.600006
854.399963,262.399994
867.199951,275.199982
879.999939,287.999969
892.799927,300.799957
905.599915,313.599945

The starting values for the point is (816, 224);

Community
  • 1
  • 1
InkGolem
  • 2,662
  • 1
  • 15
  • 22

2 Answers2

4

You are dealing with float values here. That means there will be error of that margin. If you want to round to a certain number of decimal places, use the following code:

NSString *value = [NSString stringWithFormat:@"%.1f", theFloat];

The above code rounds to 1 decimal place, which is what you need.

bibo bode
  • 1,150
  • 1
  • 10
  • 17
2

CGFloat is either a IEEE 754 single- or double-precision floating point number, which suffers from well-known accuracy problems. What you're seeing is an effect of that.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358