kev*_*kev 190 casting type-conversion swift
我想将转换Float成Int斯威夫特.像这样的基本转换不起作用,因为这些类型不是基元,与Objective-C中的floats和ints 不同
var float: Float = 2.2
var integer: Int = float as Float
但是这会产生以下错误消息:
'Float'不能转换为'Int'
知道如何将属性转换Float为Int?
iPa*_*tel 309
你可以像这样转换Float为IntSwift:
var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"
你也可以用@ paulm的评论来达到这个结果:
var myIntValue = Int(myFloatValue)
use*_*131 109
转换为Int将失去任何精度(有效地舍入).通过访问数学库,您可以执行显式转换.例如:
如果你想向下舍入并转换为整数:
let f = 10.51
let y = Int(floor(f))
结果是10.
如果你想要向上舍入并转换为整数:
let f = 10.51
let y = Int(ceil(f))
结果是11.
如果要显式 舍入到最接近的整数
let f = 10.51
let y = Int(round(f))
结果是11.
在后一种情况下,这可能看起来很迂腐,但它在语义上更清晰,因为没有隐式转换......例如,如果您正在进行信号处理,则很重要.
Art*_*nov 26
转换很简单:
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
        }
    }
}
我希望这可以帮助别人
Bor*_*zin 24
有很多方法可以精确地舍入数字.您最终应该使用swift的标准库方法rounded()以所需的精度舍入浮点数.
要整理使用.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
您可以通过将float传递给Integer初始化方法来获取float的整数表示.
例:
Int(myFloat)
请记住,小数点后的任何数字都将丢失.含义,3.9是3的Int,而8.99999是8的整数.
| 归档时间: | 
 | 
| 查看次数: | 189669 次 | 
| 最近记录: |