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
What about this approach? According to Here both Float and Double are BinaryFloatingPoint. So:
public extension Numeric where Self: BinaryFloatingPoint {
/// Returns the number of decimals. It will be always greater than 0
var numberOfDecimals: Int {
let integerString = String(Int(self))
//Avoid conversion issue
let stringNumber: String
if self is Double {
stringNumber = String(Double(self))
}
else {
stringNumber = String(Float(self))
}
let decimalCount = stringNumber.count - integerString.count - 1
return decimalCount
}
}