views:

795

answers:

2

I've got an CGFloat but need it as an NSInteger. The float value is like 2.0f, so I don't mind about fractional parts and loosing precision. What's a legal way to convert it into NSInteger without trouble (except the loss of precision, of course)?

NSInteger niceInt = niceCGFloat;

seems too simple, smells buggy. Maybe you can explain?

+1  A: 

There's always the risk that 2.0f may actually be 1.9999999999f when represented in binary. Your conversion to int would then lead to 1 instead of 2.

To avoid this, I would add 0.5f to your float value. This would also have the effect of rounding your float, instead of truncating it.

NSInteger niceInt = niceCGFloat + 0.5f;

Martin Cote
+2  A: 

You want the c function lrintf() which rounds a floating point to a long int.

groundhog