Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert double to int in swift

Tags:

swift

So I'm trying to figure out how I can get my program to lose the .0 after an integer when I don't need the any decimal places.

@IBOutlet weak var numberOfPeopleTextField: UITextField! @IBOutlet weak var amountOfTurkeyLabel: UILabel! @IBOutlet weak var cookTimeLabel: UILabel! @IBOutlet weak var thawTimeLabel: UILabel!   var turkeyPerPerson = 1.5 var hours: Int = 0 var minutes = 0.0  func multiply (#a: Double, b: Double) -> Double {     return a * b }  func divide (a: Double , b: Double) -> Double {     return a / b }  @IBAction func calculateButton(sender: AnyObject) {     var numberOfPeople = numberOfPeopleTextField.text.toInt()     var amountOfTurkey = multiply(a: 1.5, b: Double(numberOfPeople!))     var x: Double = amountOfTurkey     var b: String = String(format:"%.1f", x)     amountOfTurkeyLabel.text = "Amount of Turkey: " + b + "lbs"      var time = multiply(a: 15, b:  amountOfTurkey)     var x2: Double = time     var b2: String = String(format:"%.1f", x2)     if (time >= 60) {         time = time - 60         hours = hours + 1         minutes = time         var hours2: String = String(hours)         var minutes2: String = String(format: "%.1f", minutes)          cookTimeLabel.text = "Cook Time: " + hours2 + " hours and " + minutes2 + " minutes"     }else {         cookTimeLabel.text = "Cook Time: " + b2 + "minutes"     }  } 

}

Do I need to make an if statement to somehow turn Double into Int for this to work?

like image 430
Eric Zhou Avatar asked Aug 10 '15 09:08

Eric Zhou


People also ask

How do I convert double to Int in Swift?

We can round a double to the nearest Int by using the round() method in Swift. If the decimal value is >=. 5 then it rounds up to the nearest value. for example, it rounds the 15.7 to 16.0 .

How do you round double to nearest Int in Swift?

To round a double to the nearest integer, just use round() .


2 Answers

You can use:

Int(yourDoubleValue) 

this will convert double to int.

or when you use String format use 0 instead of 1:

String(format: "%.0f", yourDoubleValue) 

this will just display your Double value with no decimal places, without converted it to int.

like image 127
Greg Avatar answered Nov 16 '22 00:11

Greg


It is better to verify a size of Double value before you convert it otherwise it could crash.

extension Double {     func toInt() -> Int? {         if self >= Double(Int.min) && self < Double(Int.max) {             return Int(self)         } else {             return nil         }     } } 

The crash is easy to demonstrate, just use Int(Double.greatestFiniteMagnitude).

like image 45
Tomáš Linhart Avatar answered Nov 16 '22 01:11

Tomáš Linhart