I have the following situation in my code:
//maxiumumHeight and rowHeight are CGFloats
CGFloat rows = floorf(maximumHeight / rowHeight);
CGFloat height = (rows * rowHeight);
It works just fine, but I notice that when I use floor, it works fine also. I'm also confused about how to define rows, should it be an NSUInteger or CGFloat?
It seems to work fine in all scenarios, but I have a little trouble understanding floating point math and was wondering what is the optimal way to do this code? Or does it matter?
flooris fordouble(which is same asCGFloat) andfloorfis forfloat(meaning it takesfloatarguments). This comes from ol' C stuff. Since you useCGFloatstick withfloor. But, just in case, I would add a bit of tolerance, so change it to e.g.assuming these values are always strictly positive.
Often you'd convert the number of rows to integer but since you calculate a UI height with it, which is also going to be used as
CGFloatno need to use integers here. (Note if you are on watchCGFloatisfloatso there you'd want to usefloorfbut FWIW on many architecturesfloorandfloorfare one and the same).Not sure if this is what is troubling you, but floor rounds down to nearest int. So if you have e.g. 100 pixels available and you want a row to have 20 pixels, you will have
rows. What if you want it to be 21 pixels? Then
Now you need to decide. If you are going to insert 4 rows here you use
floorsinceand note that, since you use only 4 rows, the height of each row will be
pixels, a bit more (since you use less rows) than the 21 you hoped for.
If you in stead want to use 5 rows then use
ceilor ceiling sinceand here note that since you use more rows the height will be
pixels. So if the 21 you hoped for is a maximum you'd use
ceilin this particular example. If it is a minimum likewise you'd usefloor.Sometimes you may get funny and unexpected values, something like
which is why I'd add a bit of tolerance.