#12: Rounding Floating Point Numbers in Swift 3

The proposal SE-0113 introduced a structured way to round floating point numbers in Swift 3.

We now have a rounded(rule:) method (that will return a new float) and a round(rule:) method (that will alter the original float), that round a floating point number according to the choosen rule as described in the proposal:

  • .toNearestOrAwayFromZero: The result is the closest allowed value; if two values are equally close, the one with greater magnitude is chosen. Also known as “schoolbook rounding” and is the default when no rule is provided.

  • .toNearestOrEven: The result is the closest allowed value; if two values are equally close, the even one is chosen. Also known as “bankers rounding”.

  • .up: The result is the closest allowed value that is greater than or equal to the source.

  • .down: The result is the closest allowed value that is less than or equal to the source.

  • .towardZero: The result is the closest allowed value whose magnitude is less than or equal to that of the source.

  • .awayFromZero: The result is the closest allowed value whose magnitude is greater than or equal to that of the source.

Let’s see a few examples:

  
(4.4).rounded()                         // 4.0
(4.5).rounded()                         // 5.0
(4.3).rounded(.toNearestOrAwayFromZero) // 4.0
(4.5).rounded(.toNearestOrAwayFromZero) // 5.0
(4.5).rounded(.toNearestOrEven)         // 4.0
(4.3).rounded(.up)                      // 5.0
(4.3).rounded(.down)                    // 4.0
(4.7).rounded(.towardZero)              // 4.0
(4.2).rounded(.awayFromZero)            // 5.0

Did you like this article? Let me know on Twitter or subscribe for updates!


I'm also on Twitter and GitHub.

Subscribe via RSS or email.