简体   繁体   English

如何在 Swift 中将 Double 转换为 Int?

[英]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.我试图弄清楚当我不需要任何小数位时,如何让我的程序在整数后丢失.0

@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?我是否需要做一个 if 语句以某种方式将 Double 转换为 Int 才能正常工作?

You can use:您可以使用:

Int(yourDoubleValue)

this will convert double to int.这会将 double 转换为 int。

or when you use String format use 0 instead of 1:或者当您使用字符串格式时,使用 0 而不是 1:

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

this will just display your Double value with no decimal places, without converted it to int.这将只显示没有小数位的 Double 值,而不将其转换为 int。

It is better to verify a size of Double value before you convert it otherwise it could crash.最好在转换之前验证Double值的大小,否则可能会崩溃。

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) .崩溃很容易演示,只需使用Int(Double.greatestFiniteMagnitude)

A more generic way to suppress (only) the .0 decimal place in a string representation of a Double value is to use NSNumberFormatter .Double值的字符串表示中抑制(仅).0 小数位的更通用方法是使用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"

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. init(exactly:)init(:)几乎相同,唯一的区别是init(exactly:)不会崩溃,而init(:)可能会在失败的情况下调用fatalError(:)

You can check their implementations here你可以在这里查看他们的实现

Another way:另一种方式:

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

These answers really don't take into account the limitations of expressing Int.max and Int.min that Doubles have. 这些答案实际上没有考虑到表达双打的Int.max和Int.min的局限性。 Ints are 64 bit but Doubles only have 52 bits of precision in their mantissa. Int是64位,但是双尾的尾数只有52位精度。

A better answer is: 一个更好的答案是:

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

        return Int(self)
    }
}

Swift 4 - Xcode 9斯威夫特 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
}

Swift 4 - Xcode 10斯威夫特 4 - Xcode 10

Use this code to avoid a crash if the double value exceeds the int boundaries (and so isn't representable):如果 double 值超出 int 边界(因此无法表示),请使用此代码避免崩溃:

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)")
}

Swift 5 Xcode 10.3 Swift 5 Xcode 10.3

lose .0 or keep when something after decimal like .07 丢失.0或保留小数点后的内容,如.07

func doubleToIntWhenDecimalZero(number: Double) -> Any {
    if number.truncatingRemainder(dividingBy: 1.0) == 0.0 {
        return Int(number)
    } else {
        return number
    }
}
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

If you don't care for very large values use this code to clamp the Doubl to max/min Int` values.如果您不关心非常大的值,请使用此代码将双精度值限制Doubl to max/min Int` 值。

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

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

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