How to safely floor or ceil a CGFloat to int?

前端 未结 3 1343
面向向阳花
面向向阳花 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条回答
  •  猫巷女王i
    2021-02-01 20:02

    Swift supplemental answer

    I am adding this as a supplemental answer for those who come here looking how to use floor and ceil with a CGFloat (like I did).

    var myCGFloat: CGFloat = 3.001
    floor(myCGFloat) // 3.0
    ceil(myCGFloat) // 4.0
    

    And if an Int is needed, then it can be cast to one.

    var myCGFloat: CGFloat = 3.001
    Int(floor(myCGFloat)) // 3
    Int(ceil(myCGFloat)) // 4
    

    Update

    There is no need to use the C floor and ceil functions anymore. You can use the Swift round() with rounding rules.

    var myCGFloat: CGFloat = 3.001
    myCGFloat.round(.down) // 3.0
    myCGFloat.round(.up) // 4.0
    

    If you don't wish to modify the original variables, then use rounded().

    Notes

    • Works with both 32 and 64 bit architectures.

    See also

    • How to round CGFloat

提交回复
热议问题