swiftfoundation

Difference between FloatingPointRoundingRule.down and FloatingPointRoundingRule.towardsZero in Foundation


FloatingPointRoundingRule.down and FloatingPointRoundingRule.towardsZero both are rounded towards zero(rounded to nearest Int value). Then what is difference between them and at which scenario what type should be used?


Solution

  • The case towardZero acts opposite for positive and negative numbers.

    Here is an image for better understanding:

    Demo

    And based on the documentation:

    case down

    Round to the closest allowed value that is less than or equal to the source.

    (5.2).rounded(.down) // 5.0
    (5.5).rounded(.down) // 5.0
    (-5.2).rounded(.down) // -6.0
    (-5.5).rounded(.down) // -6.0
    
    case towardZero

    Round to the closest allowed value whose magnitude is less than or equal to that of the source.

    (5.2).rounded(.towardZero) // 5.0
    (5.5).rounded(.towardZero) // 5.0
    (-5.2).rounded(.towardZero) // -5.0
    (-5.5).rounded(.towardZero) // -5.0