Home > Enterprise >  How to round off Double value in swift
How to round off Double value in swift

Time:05-17

I have a double value of for e.g., 6.4299999999999997 which has to be rounded to 6.43 or 45.39999 to 45.40. I did try with round, rounded but i couldn't get the desired value. Is there a way that i can achieve in SWIFT(iOS)?

CodePudding user response:

Try this

let value = 5.4873
let roundedValue = round(value * 1000) / 1000.0
// roundedValue is 5.487

let value = 6.4299999999999997
let roundedValue = round(value * 100) / 100.0
// roundedValue is 6.43

CodePudding user response:

Try this

extension Double {

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

}

How to use it:

enter image description here

  • Related