ios swift4 – How to Round a Digit to Two Decimal Places in Swift

iosswift4

I'm getting a value of digits which i'm trying to convert to two decimal places. But when i convert it it makes the result to 0.00 . The digits are this 0.24612035420731018 . When get its .2f value it shows 0.00. The code that i tried is this,

 let  digit = FindResturantSerivce.instance.FindResModelInstance[indexPath.row].distance
    let text = String(format: "%.2f", arguments: [digit])
    print(text)

Best Answer

If you want to really round the number, and not just format it as rounded for display purposes, then I prefer something a little more general-purpose:

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

So you can then do something like:

let foo = 3.14159.rounded(digits: 3) // 3.142
Related Question