14

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"

Tzahi
  • 259
  • 3
  • 12

2 Answers2

50

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
atxe
  • 5,029
  • 2
  • 36
  • 50
  • 1
    The Swift 3 example is great thank you, but please could you tell me how i could change this to always Round Down? i.e.. let num: Double = 1.85 num.round(nearest: 0.5) // Returns 2.0 but i want to return 1.5!!! – GameDev Jun 13 '17 at 13:16
  • that would be another question... but I updated my answer ;-) – atxe Jun 15 '17 at 16:51
  • That's great thank you, but in the end I did manage to work it out once I discovered the floor function :) – GameDev Jun 17 '17 at 01:11
27
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.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123