Convert Float to Int in Swift

前端 未结 13 1862
没有蜡笔的小新
没有蜡笔的小新 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:30

    Use Int64 instead of Int. Int64 can store large int values.

    0 讨论(0)
  • 2020-11-28 23:32

    You can get an integer representation of your float by passing the float into the Integer initializer method.

    Example:

    Int(myFloat)
    

    Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

    0 讨论(0)
  • 2020-11-28 23:38

    Explicit Conversion

    Converting to Int will lose any precision (effectively rounding down). By accessing the math libraries you can perform explicit conversions. For example:

    If you wanted to round down and convert to integer:

    let f = 10.51
    let y = Int(floor(f))
    

    result is 10.

    If you wanted to round up and convert to integer:

    let f = 10.51
    let y = Int(ceil(f))
    

    result is 11.

    If you want to explicitly round to the nearest integer

    let f = 10.51
    let y = Int(round(f))
    

    result is 11.

    In the latter case, this might seem pedantic, but it's semantically clearer as there is no implicit conversion...important if you're doing signal processing for example.

    0 讨论(0)
  • 2020-11-28 23:41

    Just use type casting

     var floatValue:Float = 5.4
     var integerValue:Int = Int(floatValue)
    
     println("IntegerValue = \(integerValue)")
    

    it will show roundoff value eg: IntegerValue = 5 means the decimal point will be loss

    0 讨论(0)
  • 2020-11-28 23:42

    You can convert Float to Int in Swift like this:

    var myIntValue:Int = Int(myFloatValue)
    println "My value is \(myIntValue)"
    

    You can also achieve this result with @paulm's comment:

    var myIntValue = Int(myFloatValue)
    
    0 讨论(0)
  • 2020-11-28 23:42
    var i = 1 as Int
    
    var cgf = CGFLoat(i)
    
    0 讨论(0)
提交回复
热议问题