我得到一个数字值,我试图将其转换为两位小数。但是当我转换它时,结果为0.00。数字是0.24612035420731018
。获得其.2f值时,它显示0.00。我试过的代码就是这个,
let digit = FindResturantSerivce.instance.FindResModelInstance[indexPath.row].distance
let text = String(format: "%.2f", arguments: [digit])
print(text)
答案 0 :(得分:10)
如果您想真正舍入数字,而不仅仅是将其格式化为用于显示目的的舍入,那么我更喜欢一些通用的东西:
extension Double {
func rounded(digits: Int) -> Double {
let multiplier = pow(10.0, Double(digits))
return (self * multiplier).rounded() / multiplier
}
}
因此您可以执行以下操作:
let foo = 3.14159.rounded(digits: 3) // 3.142
答案 1 :(得分:7)
使用格式字符串将最多两位小数舍入并将double转换为String:
let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)
示例:
let myDouble = 3.141
let doubleStr = Double(String(format: "%.2f", myDouble)) // 3.14
let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"
如果你要整理你的最后一个小数位,你可以这样做:
let myDouble = 3.141
let doubleStr = Double(String(format: "%.2f", ceil(myDouble*100)/100)) // 3.15
let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"