如何将currentRatio四舍五入到小数点后两位?
let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)! railRatioLabelField.text! = "\(currentRatio)"
使用格式字符串将最多两位小数舍入并将double转换为String:
let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)! railRatioLabelField.text! = String(format: "%.2f",currentRatio)
例:
let myDouble = 3.141 let doubleStr = String(format: "%.2f",myDouble) // "3.14"
如果你想要整理你的最后一个小数位,你可以做这样的事情(感谢Phoen1xUK):
let myDouble = 3.141 let doubleStr = String(format: "%.2f",ceil(myDouble*100)/100) // "3.15"