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