I often need to floor or ceil a CGFloat to an int, for calculation of an array index.
The problem I permanently see with floorf(theCGFloat) or ceilf(theCGFloat) is that there can be troubles with floating point inaccuracies.
So what if my CGFloat is 2.0f but internally it is represented as 1.999999999999f or something like that. I do floorf and get 1.0f, which is a float again. And yet I must cast this beast to int which may introduce another problem.
Is there a best practice how to floor or ceil a float to an int such that something like 2.0 would never accidentally get floored to 1 and something like 2.0 would never accidentally get ceiled to 2?
There are a couple misconceptions in your question.
can’t happen; 2.0, like all reasonably small integers, has an exact representation in floating-point. If your
CGFloatis2.0f, then it really is 2.0.The ceiling of 2.0 is 2; what else would it possibly be?
I think the question that you’re really asking is “suppose I do a calculation that produces an inexact result, which mathematically should be exactly 2.0, but is actually slightly less; when I apply
floorto that value, I get 1.0 instead of 2.0–how do I prevent this?”That’s actually a fairly subtle question that doesn’t have a single “right” answer. How have you computed the input value? What are you going to do with the result?