我想在Swift中转换浮点数为Int。像这样的基本强制转换不起作用,因为这些类型不是基本类型,不像Objective-C中的float和int类型
var float: Float = 2.2
var integer: Int = float as Float
但是这会产生以下错误消息:
Float不能转换为Int
知道如何将属性从Float转换为Int吗?
我想在Swift中转换浮点数为Int。像这样的基本强制转换不起作用,因为这些类型不是基本类型,不像Objective-C中的float和int类型
var float: Float = 2.2
var integer: Int = float as Float
但是这会产生以下错误消息:
Float不能转换为Int
知道如何将属性从Float转换为Int吗?
当前回答
转换很简单:
let float = Float(1.1) // 1.1
let int = Int(float) // 1
但这并不安全:
let float = Float(Int.max) + 1
let int = Int(float)
将由于一次漂亮的碰撞:
fatal error: floating point value can not be converted to Int because it is greater than Int.max
所以我已经创建了一个处理溢出的扩展:
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
}
}
}
我希望这能帮助到一些人
其他回答
使用函数样式的转换(参见“Swift编程语言”中的“整数和浮点转换”一节)。(iTunes链接))
1> Int(3.4)
$R1: Int = 3
var floatValue = 10.23
var intValue = Int(floatValue)
这足以将float转换为Int
这里介绍的大多数解决方案对于较大的值都会崩溃,不应该在生产代码中使用。
如果你不关心非常大的值,使用这段代码来夹紧Double到max/min Int值。
let bigFloat = Float.greatestFiniteMagnitude
let smallFloat = -bigFloat
extension Float {
func toIntTruncated() -> Int {
let maxTruncated = min(self, Float(Int.max).nextDown)
let bothTruncated = max(maxTruncated, Float(Int.min))
return Int(bothTruncated)
}
}
// This crashes:
// let bigInt = Int(bigFloat)
// this works for values up to 9223371487098961920
let bigInt = bigFloat.toIntTruncated()
let smallInt = smallFloat.toIntTruncated()
有很多方法可以精确地取整数。您最终应该使用swift的标准库方法roundaround()来以所需的精度舍入浮点数。
取整use .up规则:
let f: Float = 2.2
let i = Int(f.rounded(.up)) // 3
向下舍入使用.down规则:
let f: Float = 2.2
let i = Int(f.rounded(.down)) // 2
要四舍五入到最接近的整数,请使用.toNearestOrEven规则:
let f: Float = 2.2
let i = Int(f.rounded(.toNearestOrEven)) // 2
请注意以下示例:
let f: Float = 2.5
let i = Int(roundf(f)) // 3
let j = Int(f.rounded(.toNearestOrEven)) // 2
是这样的:
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