I want to count the number of decimal places (ignoring trailing zeros) in a Float (or NSDecimalNumber) for example:
1.45000 => 2
5.98 => 2
1.00 => 0
0.8
For me, there is quite easy solution that works on any region and device because iOS will handle possible binary errors for you automatically:
extension Double {
func decimalCount() -> Int {
if self == Double(Int(self)) {
return 0
}
let integerString = String(Int(self))
let doubleString = String(Double(self))
let decimalCount = doubleString.count - integerString.count - 1
return decimalCount
}
}
Edit: it should work same for Double or Float