将字符串值从格式为双精度的服务器转换为整数



我使用一种服务,该服务发送回类型为String的值,其中包含像Double这样的浮点数,例如"1240.86"。 我想将其转换为Int,当我尝试像这样转换时Int(stringObject)当值具有浮点数时,转换失败。 如何投射? 谢谢!

分两步尝试:

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

或者可能:

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

尽管后者有点笨拙,因为如果字符串不是有效数字,您可能不想强制使用0的值。

您可以使用map(_:)Optional方法选择性地将转换(特别是初始化方式(从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
}

你可以用点分隔字符串.

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

最新更新