How to safely floor or ceil a CGFloat to int?

前端 未结 3 1380
面向向阳花
面向向阳花 2021-02-01 19:01

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(theCGFloa

3条回答
  •  耶瑟儿~
    2021-02-01 20:01

    EDIT - read the comments for reasons why this answer isn't right :)

    Casting a float to an int is an implicit floorf i.e. (int)5.9 is 5. If you don't mind that then just cast :)

    If you want to round up then just cast the result of a ceilf - casting after rounding shouldn't introduce any errors at all (or, if you want, add one before casting i.e. `(int)(5.9+1)' is '6' - same as rounding up).

    To round to the nearest, just add 0.5 - (int)(5.9+0.5) is 6 but (int)(5.4+0.5) is 5. Though I would just use roundf(5.9) :)

提交回复
热议问题