Rounding a double value to x number of decimal places in swift

by sisccr

A little extension I wrote in Swift to round off the numbers to required number of decimal places.

 
extension Double {
    func roundOff(precision: Double) -> Double {
        let multiplier = pow(10.0, precision)
        let y = Double(round(multiplier * self) / multiplier)  // round function takes decimal value and returns double without decimals. round(123.456) --> 123
        return y
        }
}

 

Usage:

 
let x = 123.456

x.roundOff(1)  --> 123.5

x.roundOff(2) --> 123.46

x.roundOff(2) --> 123.456
Advertisements