我的问题是我如何得到我的"计算"和"计算总数"变量将结果显示为仅两位小数?
@IBOutlet weak var calculateLabel: UILabel!
@IBOutlet weak var calculateTotalLabel: UILabel!
@IBAction func calculateButton(sender: UIButton) {
var calculated = correctNumber / (correctNumber + incorrectNumber) * 100
calculateLabel.text = ("\(calculated)% without cues.")
var calculatedTotal = correctNumber / (correctNumber + incorrectNumber + verbalNumber + visualNumber + tactileNumber) * 100
calculateTotalLabel.text = "\(calculatedTotal)% without cues."
}
答案 0 :(得分:2)
您可以在Swift中使用类似C的格式说明符,如下所示:
println(String(format: "%.2f", myFloat))
或
calculatedTotal.text = String(format: "%.2f", myFloat)
答案 1 :(得分:2)
为最终用户格式化数字时,我建议使用NSNumberFormatter
,以尊重用户当前的NSLocale
。例如,要将这些数字格式化为两位小数,您可能会执行以下操作:
@IBAction func calculateButton(sender: UIButton) {
let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let calculated = correctNumber / (correctNumber + incorrectNumber) * 100.0
calculateLabel.text = ("\(formatter.stringFromNumber(calculated)!)% without cues.")
let calculatedTotal = correctNumber / (correctNumber + incorrectNumber + verbalNumber + visualNumber + tactileNumber) * 100.0
calculateTotalLabel.text = "\(formatter.stringFromNumber(calculatedTotal)!)% without cues."
}