CrazyPython CrazyPython - 7 months ago 21
Swift Question

Easily truncating a Double - swift

I want to be able to take a longitude/latitude value of 19.3563443 and turn it into 19.35634 (five decimal places). Is there any easy way to do this?

Answer

You can use NSNumberFormatter():

extension Double {
    var roundTo5:Double {
        let converter = NSNumberFormatter()
        let formatter = NSNumberFormatter()
        formatter.numberStyle = NSNumberFormatterStyle.NoStyle
        formatter.minimumFractionDigits = 5
        formatter.roundingMode = .RoundDown
        formatter.maximumFractionDigits = 5
        if let stringFromDouble =  formatter.stringFromNumber(self) {
            if let doubleFromString = converter.numberFromString( stringFromDouble ) as? Double {
                return doubleFromString
            }
        }
        return 0
    }
}

Double(19.3563443 ).roundTo5   // 1.935634e+1
Comments