如何在swift中将double转换为int

时间:2015-08-10 09:18:26

标签: swift

因此,当我不需要任何小数位时,我试图找出如何让我的程序在整数后丢失.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"
    }

}

}

我是否需要制作一个if语句以某种方式将Double转换为Int才能使其正常工作?

11 个答案:

答案 0 :(得分:79)

您可以使用:

Int(yourDoubleValue)

这会将double转换为int。

或使用String格式时使用0而不是1:

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

这将只显示没有小数位的Double值,而不将其转换为int。

答案 1 :(得分:25)

最好在转换之前验证<?php for($i=0; $i<10; $i++) { echo '<tr class="multipp">'; echo '<td><input type="text" name="description_'.$i.'" id="description_'.$i.'" size="85" maxlength="70" value="'.htmlspecialchars($description[$i]).'" /></td>'; echo '<td><input type="text" name="priceper_'.$i.'" id="priceper_'.$i.'" size="10" maxlength="9" value="'.htmlspecialchars($priceper[$i]).'" /></td>'; echo '<td><input type="text" name="per_pack_'.$i.'" id="per_pack_'.$i.'" class="txt" size="10" maxlength="9" value="'.htmlspecialchars($priceper[$i]).'" /></td>'; echo '<td><input type="text" name="quantity_'.$i.'" id="quantity_'.$i.'" size="10" maxlength="9" value="'.htmlspecialchars($quantity[$i]).'" />`</td>'; echo '<td><input type="text" name="subtotal_'.$i.'" id="subtotal_'.$i.'" size="15" maxlength="9" value="'.htmlspecialchars($subtotal[$i]).'" /></td>'; echo '</tr>'; } ?> 值的大小,否则可能会崩溃。

Double

崩溃很容易证明,只需使用extension Double { func toInt() -> Int? { if self >= Double(Int.min) && self < Double(Int.max) { return Int(self) } else { return nil } } }

答案 2 :(得分:3)

Double值的字符串表示中抑制(仅).0小数位的更通用的方法是使用NSNumberFormatter。它还考虑当前语言环境的数字格式。

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

答案 3 :(得分:2)

这些答案确实没有考虑到Doubles表示Int.max和Int.min的局限性。整数是64位,但Doubles的尾数只有52位精度。

一个更好的答案是:

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

        return Int(self)
    }
}

答案 4 :(得分:1)

应该起作用:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);
        }
    }

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

您可以在此处查看其实现

答案 5 :(得分:0)

Swift 4 - Xcode 9

var d = '12-4-88'; // '25.10.2018'; or 25.10.18 or 25-12-2018

d = d.split(/[.\-_]/);
d.forEach((v,k) => {
  if(v < 10) d[k] = 0 + v;
  if(k == 2 && v.length == 2) {
     var year = new Date(v+"-01-01");
     d[k] = year.getFullYear();
   }
})

console.log(d[0] + '/' + d[1] + '/' + d[2]);

答案 6 :(得分:0)

Swift 4-Xcode 10

如果double值超出int边界,请使用以下代码避免崩溃:

将此私人扩展名添加到您的班级:

private extension Int {

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

    self.init(doubleVal)
}

以这种方式在您的班级中使用扩展名:

func test() {

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

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

答案 7 :(得分:0)

Swift 5 Xcode 10.3

丢失.0或保留小数点后的内容,例如.07

func doubleToIntWhenDecimalZero(number: Double) -> Any {
    if number.truncatingRemainder(dividingBy: 1.0) == 0.0 {
        return Int(number)
    } else {
        return number
    }
}

答案 8 :(得分:0)

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

测试结果

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

答案 9 :(得分:0)

另一种方式

extension Double {

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

}

  

答案 10 :(得分:0)

如果您不关心非常大的值,请使用此代码来限制 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()