How to safely create an NSInteger from CGFloat?

I have CGFloat, but I need it as NSInteger. The float value is 2.0f, so I do not mind fractional parts and loss of precision. What is a legitimate way to convert it to NSInteger immediately (except for loss of accuracy, of course)?

NSInteger niceInt = niceCGFloat; 

It seems too simple, it smells like a buggy. Maybe you can explain?

+4
source share
2 answers

You need a function c lrintf () that rounds a floating point to a long int.

+7
source

There is always the risk that 2.0f could be 1.9999999999f if it is in binary format. Then your conversion to int will result in 1 instead of 2.

To avoid this, I would add 0.5f to your float value. It will also affect the rounding of your float, not its shortening.

NSInteger niceInt = niceCGFloat + 0.5f;

+6
source

All Articles