shadox
shadox

Reputation: 1003

Convert Int to Double in Swift

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

The above code returns this error:

'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.

Upvotes: 65

Views: 95495

Answers (3)

EgzonArifi
EgzonArifi

Reputation: 830

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:

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.

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

Upvotes: 9

Malik
Malik

Reputation: 947

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

Upvotes: 4

YogevSitton
YogevSitton

Reputation: 10108

Try Double(theOrder.bookingMins)

Upvotes: 144

Related Questions