我想在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吗?
当前回答
使用函数样式的转换(参见“Swift编程语言”中的“整数和浮点转换”一节)。(iTunes链接))
1> Int(3.4)
$R1: Int = 3
其他回答
假设你在“X”中存储浮点值,而在“Y”中存储整数值。
Var Y = Int(x);
or
var myIntValue = Int(myFloatValue)
转换很简单:
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的标准库方法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
您可以使用计算属性制作一个方便的扩展,并从项目中的任何地方使用它
extension Float{
var toInt : Int{
return Int(self)
}
}
调用
private var call: Float = 55.9
print(call.toInt)