#15: Rounding Floating Point Numbers to Specific Decimal Places

As described in this post, since Swift 3.0 is now possible to round floating point numbers through new methods added to the Double and Float types.

But what about rounding a number to a specific number of decimal positions?

The Manual Way

If you don’t want to depend on external frameworks, we can just do it manually, extending for example the Double type:


extension Double {
    func roundTo(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

And then simply call the method specifying the desired precision:


let x = Double(0.123456789).roundTo(places: 4) 

The Foundation Way

If you just need this conversion to print the number or use it inside a String, and that’s the case most of the times, a straightforward alternative is to just use the additional String initializer provided by Foundation that allows to specify a format:


import Foundation

String(format: "%.4f", 0.123456789)

Did you like this article? Let me know on Twitter or subscribe for updates!


I'm also on Twitter and GitHub.

Subscribe via RSS or email.