How to truncate decimals to x places in Swift

前端 未结 9 1929
Happy的楠姐
Happy的楠姐 2020-12-04 01:26

In my swift program, I have a really long decimal number (say 17.9384693864596069567) and I want to truncate the decimal to a few decimal places (so I want the

9条回答
  •  温柔的废话
    2020-12-04 02:19

    extension Double {
        /// Rounds the double to decimal places value
        func roundToPlaces(_ places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self * divisor).rounded() / divisor
        }
        func cutOffDecimalsAfter(_ places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self*divisor).rounded(.towardZero) / divisor
        }
    }
    
    let a:Double = 1.228923598
    
    print(a.roundToPlaces(2)) // 1.23
    print(a.cutOffDecimalsAfter(2)) // 1.22
    

提交回复
热议问题