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