Convert Float to Int in Swift

前端 未结 13 1863
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 23:16

I want to convert a Float to an Int in Swift. Basic casting like this does not work because these types are not primitives, unlike float

相关标签:
13条回答
  • 2020-11-28 23:45

    There are lots of ways to round number with precision. You should eventually use swift's standard library method rounded() to round float number with desired precision.

    To round up use .up rule:

    let f: Float = 2.2
    let i = Int(f.rounded(.up)) // 3
    

    To round down use .down rule:

    let f: Float = 2.2
    let i = Int(f.rounded(.down)) // 2
    

    To round to the nearest integer use .toNearestOrEven rule:

    let f: Float = 2.2
    let i = Int(f.rounded(.toNearestOrEven)) // 2
    

    Be aware of the following example:

    let f: Float = 2.5
    let i = Int(roundf(f)) // 3
    let j = Int(f.rounded(.toNearestOrEven)) // 2
    
    0 讨论(0)
提交回复
热议问题