Count number of decimal places in a Float (or Decimal) in Swift

后端 未结 5 1522
长情又很酷
长情又很酷 2021-02-06 05:43

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         


        
5条回答
  •  醉酒成梦
    2021-02-06 06:28

    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

提交回复
热议问题