round double to 0.5

前端 未结 2 984
醉梦人生
醉梦人生 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
    
    0 讨论(0)
  • 2021-02-20 04:15
    x = 13000 / 9000.0;
    
    denominator = 2;
    a.text = String(round(x*denominator )/denominator );
    

    First convert 1.444 to 2.888, then round to 3.0 and then divide by 2 to get 1.5. In this case, the denominator of 0.5 is 2 (i.e. 1/2). If you want to round to nearest quarter (0.25,0.5, 0.75, 0.00), then denominator=4

    I Should point out that this works perfectly if the denominator is a power of 2. If it is not, say denominator=3, then you can get weird answers like 1.99999999 instead of 2 for particular values.

    0 讨论(0)
提交回复
热议问题