round double to 0.5

你说的曾经没有我的故事 提交于 2020-01-22 19:00:38

问题


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 this is round to "1.0" and i need round to "1.5"

and this code :

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

is round to "2.0"


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/34460823/round-double-to-0-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!