简体   繁体   English

在 Swift 中将 Int 转换为 Double

[英]Convert Int to Double in Swift

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? bookingMins是 Int 类型,那么如何在 Swift 中将 Int 转换为 Double? Seems not as simple as in C.似乎不像在 C 中那么简单。

尝试Double(theOrder.bookingMins)

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使用的风格指南: https : //github.com/raywenderlich/swift-style-guide

label.text = String(format:"%.1f hour", Double(theOrder.bookingMins) /60.0)

Swift 4/5斯威夫特 4/5

let mins = Double(theOrder.bookingMins)
label.text = String(format:"%.1f hour", mins/60.0)

Swift 5 (Basic to Convert Int to Double) Swift 5(将 Int 转换为 Double 的基础)

let a = 3, let b =4

func divide ( number1 : Int, number2 : Int)
{
let divide = Double (number1) / Double (number2)
print (divide)

}

The output should be 0.75输出应该是 0.75

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM