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