round double to 0.5

前端 未结 2 989
醉梦人生
醉梦人生 2021-02-20 03:42

i have a result \"1.444444\" and i want to round this result to \"1.5\" this is the code i use :

a.text = String(round(13000 / 9000.0))

but thi

2条回答
  •  终归单人心
    2021-02-20 04:10

    Swift 3:

    extension Double {
        func round(nearest: Double) -> Double {
            let n = 1/nearest
            let numberToRound = self * n
            return numberToRound.rounded() / n
        }
    
        func floor(nearest: Double) -> Double {
            let intDiv = Double(Int(self / nearest))
            return intDiv * nearest
        }
    }
    
    let num: Double = 4.7
    num.round(nearest: 0.5)      // Returns 4.5
    
    let num2: Double = 1.85
    num2.floor(nearest: 0.5)     // Returns 1.5
    

    Swift 2:

    extension Double {
        func roundNearest(nearest: Double) -> Double {
            let n = 1/nearest
            return round(self * n) / n
        }
    }
    
    let num: Double = 4.7
    num.roundNearest(0.5)      // Returns 4.5
    

提交回复
热议问题