You can extend FloatingPoint
to check if it is a whole number and use a condition to set the minimumFractionDigits
property of the NumberFormatter
to 0 in case it is true otherwise set it to 2:
extension Formatter {
static let custom: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}()
}
extension FloatingPoint {
var isWholeNumber: Bool { isNormal ? self == rounded() : isZero }
var custom: String {
Formatter.custom.minimumFractionDigits = isWholeNumber ? 0 : 2
return Formatter.custom.string(for: self) ?? ""
}
}
Playground testing:
1.0.custom // "1"
1.5.custom // "1.50"
1.75.custom // "1.75"