Convert Int to Double in Swift

IosSwift

Ios Problem Overview


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

The above code just get the 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.

Ios Solutions


Solution 1 - Ios

Try Double(theOrder.bookingMins)

Solution 2 - Ios

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

Solution 3 - Ios

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

Solution 4 - Ios

Swift 5 (Basic to Convert Int to 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

Solution 5 - Ios

Swift 4/5

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshadoxView Question on Stackoverflow
Solution 1 - IosYogevSittonView Answer on Stackoverflow
Solution 2 - IosEgzonArifiView Answer on Stackoverflow
Solution 3 - IosMalikView Answer on Stackoverflow
Solution 4 - IosIkmal AzmanView Answer on Stackoverflow
Solution 5 - IosKrunal PatelView Answer on Stackoverflow