将字符串值从服务器格式化为Double转换为Int

时间:2017-07-17 15:23:19

标签: swift int

我正在使用一种服务,该服务发回类型为String的值,其中包含Double等浮点,例如" 1240.86"。 我想把它转换为Int,当我尝试像Int(stringObject)那样进行转换时,当值具有浮点时,转换会失败。 我该如何施展它? 谢谢!

3 个答案:

答案 0 :(得分:3)

Try it in two steps:

if let aDouble = Double(someString) {
    let someInt = Int(aDouble)
}

or possibly:

let someInt = Int(Double(someString) ?? 0)

though the latter is a bit of a kludge since you probably don't want to force a value of 0 if the string isn't a valid number.

答案 1 :(得分:2)

您可以使用Optional的{​​{3}}方法,有选择地将String之间的转化(通过具体初始化)链接到Double,后跟来自Double的转化} Int并有条件地绑定结果整数,如果它不是nil(即成功转换):

let str = "1240.86"
if let number = Double(str).map(Int.init) {
    // number is of type Int and, in this example, of value 1240
}

答案 2 :(得分:0)

您可以按点.分隔字符串:

func printInt(from str: String) {
    let intValue = Int(str.components(separatedBy: ".")[0]) ?? 0
    print(intValue)
}

printInt(from: "1234.56")   // 1234
printInt(from: "1234")      // 1234
printInt(from: "0.54")      // 0
printInt(from: ".54")       // 0
printInt(from: "abc")       // 0