所以我想弄清楚如何在一个整数之后让我的程序失去.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"
}
}
Run Code Online (Sandbox Code Playgroud)
}
我是否需要制作一个if语句以某种方式将Double转换为Int以使其工作?
Gre*_*reg 91
您可以使用:
Int(yourDoubleValue)
Run Code Online (Sandbox Code Playgroud)
这会将double转换为int.
或者当您使用String格式时使用0而不是1:
String(format: "%.0f", yourDoubleValue)
Run Code Online (Sandbox Code Playgroud)
这将只显示没有小数位的Double值,而不将其转换为int.
Tom*_*art 31
最好Double在转换之前验证值的大小,否则可能会崩溃.
extension Double {
func toInt() -> Int? {
if self >= Double(Int.min) && self < Double(Int.max) {
return Int(self)
} else {
return nil
}
}
}
Run Code Online (Sandbox Code Playgroud)
崩溃很容易证明,只需使用Int(Double.greatestFiniteMagnitude).
那应该有效:
// 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")
}
Run Code Online (Sandbox Code Playgroud)
init(exactly:)与 几乎相同init(:),唯一的区别是init(exactly:)不会崩溃,但可能会在失败时init(:)调用。fatalError(:)
你可以在这里检查他们的实现
其他方式:
extension Double {
func toInt() -> Int? {
let roundedValue = rounded(.toNearestOrEven)
return Int(exactly: roundedValue)
}
}
Run Code Online (Sandbox Code Playgroud)
抑制(仅)Double值的字符串表示中的 .0 小数位的更通用方法是使用NSNumberFormatter. 它还考虑当前语言环境的数字格式。
let x : Double = 2.0
let doubleAsString = NumberFormatter.localizedString(from: (NSNumber(value: x), numberStyle: .decimal)
// --> "2"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45464 次 |
| 最近记录: |