Convert Float to Int in Swift

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

    Suppose you store float value in "X" and you are storing integer value in "Y".

    Var Y = Int(x);
    

    or

    var myIntValue = Int(myFloatValue)
    
    0 讨论(0)
  • 2020-11-28 23:23
    var floatValue = 10.23
    var intValue = Int(floatValue)
    

    This is enough to convert from float to Int

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

    You can type cast like this:

     var float:Float = 2.2
     var integer:Int = Int(float)
    
    0 讨论(0)
  • 2020-11-28 23:27

    Converting is simple:

    let float = Float(1.1) // 1.1
    let int = Int(float) // 1
    

    But it is not safe:

    let float = Float(Int.max) + 1
    let int = Int(float)
    

    Will due to a nice crash:

    fatal error: floating point value can not be converted to Int because it is greater than Int.max
    

    So I've created an extension that handles overflow:

    extension Double {
        // If you don't want your code crash on each overflow, use this function that operates on optionals
        // E.g.: Int(Double(Int.max) + 1) will crash:
        // fatal error: floating point value can not be converted to Int because it is greater than Int.max
        func toInt() -> Int? {
            if self > Double(Int.min) && self < Double(Int.max) {
                return Int(self)
            } else {
                return nil
            }
        }
    }
    
    
    extension Float {
        func toInt() -> Int? {
            if self > Float(Int.min) && self < Float(Int.max) {
                return Int(self)
            } else {
                return nil
            }
        }
    }
    

    I hope this can help someone

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

    Like this:

    var float:Float = 2.2 // 2.2
    var integer:Int = Int(float) // 2 .. will always round down.  3.9 will be 3
    var anotherFloat: Float = Float(integer) // 2.0
    
    0 讨论(0)
  • 2020-11-28 23:28

    Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])

      1> Int(3.4)
    $R1: Int = 3
    
    0 讨论(0)
提交回复
热议问题