How I can print Double with 2 digit after point and hide if they are zero?
5.12345 -> 5.12
5.00000 -> 5
5.10000 -> 5.10
How I can print Double with 2 digit after point and hide if they are zero?
5.12345 -> 5.12
5.00000 -> 5
5.10000 -> 5.10
You could try this
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"