Eric Zhou
Eric Zhou

Reputation: 965

How to convert Double to Int in Swift?

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?

Upvotes: 87

Views: 114233

Answers (10)

Rishabh
Rishabh

Reputation: 391

  1. Convert double to NSNumber
  2. Use .int64Value var for Int64 and .intValue for Int
  3. I am storing long int values like timestamp so using Int64 for precision

Note:

Conversion from double to Int and Int(someDouble) can give you an exception error on range exceed case So using Int64(someDouble) and Int(someDouble) is both not suitable whereas NSNumber(floatLiteral: value_InDouble).intValue will not give you any such error.


  let value_Int64 = NSNumber(floatLiteral: value_InDouble).int64Value

OR

  let value_Int = NSNumber(floatLiteral: value_InDouble).intValue

Upvotes: 1

Alexander Khitev
Alexander Khitev

Reputation: 6851

Another way:

extension Double {
    
    func toInt() -> Int? {
        let roundedValue = rounded(.toNearestOrEven)
        return Int(exactly: roundedValue)
    }
    
}

Upvotes: 8

Vishal Vaghasiya
Vishal Vaghasiya

Reputation: 4901

Swift 4 - Xcode 9

let value = doubleToInteger(data:"ENTER DOUBLE VALUE")

func doubleToInteger(data:Double)-> Int {
    let doubleToString = "\(data)"
    let stringToInteger = (doubleToString as NSString).integerValue
            
    return stringToInteger
}

Upvotes: 0

de.
de.

Reputation: 8457

If you don't care for very large values use this code to clamp the Doubl to max/min Int` values.

let bigDouble   = Double.greatestFiniteMagnitude
let smallDouble = -bigDouble

extension Double {
    func toIntTruncated() -> Int {
        let maxTruncated  = min(self, Double(Int.max).nextDown) // Nota bene: crashes without `nextDown`
        let bothTruncated = max(maxTruncated, Double(Int.min))
        return Int(bothTruncated)
    }
}

let bigDoubleInt   = bigDouble.toIntTruncated()
let smalDoublelInt = smallDouble.toIntTruncated()

Upvotes: 0

Hun
Hun

Reputation: 3798

extension Double {
  var prettyWeight: String {
    Int(exactly: self) == nil ? "\(self)kg" : "\(Int(self))kg"
  }
}

test result

for i in stride(from: 0.5, to: 10, by: 0.5) {
  print("\(i): \(i.prettyWeight)")
}

0.5: 0.5kg
1.0: 1kg
1.5: 1.5kg
2.0: 2kg
2.5: 2.5kg
3.0: 3kg
3.5: 3.5kg
4.0: 4kg
4.5: 4.5kg
5.0: 5kg
5.5: 5.5kg
6.0: 6kg
6.5: 6.5kg
7.0: 7kg
7.5: 7.5kg
8.0: 8kg
8.5: 8.5kg
9.0: 9kg
9.5: 9.5kg

Upvotes: -1

Mert Buran
Mert Buran

Reputation: 3017

that should work:

// round your double so that it will be exactly-convertible
if let converted = Int(exactly: double.rounded()) {
  doSomethingWithInteger(converted)
} else {
  // double wasn't convertible for a reason, it probably overflows
  reportAnError("\(double) is not convertible")
}

init(exactly:) is almost the same with init(:), the only difference is that init(exactly:) doesn't crash while init(:) may call fatalError(:) in case of failure.

You can check their implementations here

Upvotes: 8

Jochen Holzer
Jochen Holzer

Reputation: 1736

Swift 4 - Xcode 10

Use this code to avoid a crash if the double value exceeds the int boundaries (and so isn't representable):

Add this private extension to your class:

private extension Int {

    init?(doubleVal: Double) {
        guard (doubleVal <= Double(Int.max).nextDown) && (doubleVal >= Double(Int.min).nextUp) else {
        return nil
    }

    self.init(doubleVal)
}

Use the extension in your class this way:

func test() {

    let d = Double(123.564)
    guard let intVal = Int(doubleVal: d) else {
        print("cannot be converted")
    }

    print("converted: \(intVal)")
}

Upvotes: 0

Tom&#225;š Linhart
Tom&#225;š Linhart

Reputation: 14299

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

Upvotes: 65

vadian
vadian

Reputation: 285079

A more generic way to suppress (only) the .0 decimal place in a string representation of a Double value is to use NSNumberFormatter. It considers also the number format of the current locale.

let x : Double = 2.0
let doubleAsString = NumberFormatter.localizedString(from: (NSNumber(value: x), numberStyle: .decimal) 
// --> "2"

Upvotes: 6

Greg
Greg

Reputation: 25459

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.

Upvotes: 158

Related Questions