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?
Asked
Active
Viewed 32 times
-2

iroh
- 23
- 5
-
1"both are rounded towards zero" No. Did you forget about negative numbers? – Sweeper Jul 08 '23 at 10:25
-
"rounded to nearest Int value", this isn't completely correct either depending on the context. – Joakim Danielson Jul 08 '23 at 12:28
1 Answers
2
The case towardZero
acts opposite for positive and negative numbers.
Here is an image for better understanding:
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