如何在点后用两位数字打印Double并隐藏是否为零?
5.12345-> 5.12
5.00000-> 5
5.10000-> 5.10
答案 0 :(得分:1)
您可以尝试
func format(_ x: Double) -> String {
if Double(Int(x)) == x {
return String(Int(x))
} else {
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
guard let s = numberFormatter.string(for: x) else {
fatalError("Couldn't format number")
}
return s
}
}
format(5.12) //"5.12"
format(5.0) //"5"
format(5.10) //"5.10"