0

What's the formula for Banker's rounding in Swift language?

For example: 134.5675 becomes 134 and 135.5345 becomes 136

Thus far I've tried something like this:

extension Double {
    func roundHalfToEven() -> Double {
        return round(self * 100) / 100
    }
}

But it's nowhere near returns what I need.

1 Answers1

3

Remove multiplying and dividing by 100. Then use lrint (instead of round), which rounds the input to the nearest integer.

Artal
  • 8,933
  • 2
  • 27
  • 30
  • Bankers rounding is supposed to be "round half even" which is not the same as round to the nearest integer – aeropapa17 Nov 17 '17 at 01:34
  • @aeropapa17 maybe there was something confusing in the way I put it, but the fact is that `lrint` returns the nearest integer according to the current rounding mode, which is by default the nearest integer (FE_TONEAREST), which is actually "nearest even", AKA "banker's rounding": lrint(1.5) = 2, lrint(2.5) = 2, lrint(3.234) = 3, lrint(3.5) = 4, lrint(4.6) = 5 – Artal Nov 18 '17 at 09:37
  • My mistake. Thanks for clarifying. – aeropapa17 Nov 18 '17 at 13:08