ios 在 Swift 中将 Int 转换为 Double
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27467888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Int to Double in Swift
提问by shadox
label.text = String(format:"%.1f hour", theOrder.bookingMins/60.0)
The above code just get the error:'Int' is not convertible to 'Double'
上面的代码只是得到错误:'Int' is not convertible to 'Double'
bookingMins
is of type Int, so how do I convert an Int to a Double in Swift? Seems not as simple as in C.
bookingMins
是 Int 类型,那么如何在 Swift 中将 Int 转换为 Double?似乎不像在 C 中那么简单。
回答by YogevSitton
Try Double(theOrder.bookingMins)
尝试 Double(theOrder.bookingMins)
回答by EgzonArifi
What I prefer to do is to use computed properties. So I like to create an extension of Double and than add a property like below:
我更喜欢做的是使用计算属性。所以我喜欢创建 Double 的扩展,而不是添加如下属性:
extension Int {
var doubleValue: Double {
return Double(self)
}
}
And than you can use it in very Swifty way, I believe in future updates of swift language will be something similar.
比起您可以非常 Swifty 的方式使用它,我相信 Swift 语言的未来更新将是类似的。
let bookingMinutes = theOrder.bookingMins.doubleValue
in your case
在你的情况下
label.text = String(format: "%.1f hour", bookingMinutes / 60.0)
Style guide used: https://github.com/raywenderlich/swift-style-guide
回答by Mo Abdulmalik
label.text = String(format:"%.1f hour", Double(theOrder.bookingMins) /60.0)
回答by Krunal Patel
Swift 4/5
斯威夫特 4/5
let mins = Double(theOrder.bookingMins)
label.text = String(format:"%.1f hour", mins/60.0)