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

后端 未结 5 1514
长情又很酷
长情又很酷 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:21

    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
        }
        
    }
    

提交回复
热议问题