Question

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);

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top