-2

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?

iroh
  • 23
  • 5

1 Answers1

2

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
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278