2

Does rounding rules for .5 applies also for .05, .005 etc? I couldn't figure out why rounding for 45.445 and 73.445 differ.

> round(45.445,2)
[1] 45.45
> round(73.445,2)
[1] 73.44
Alberson Miranda
  • 1,248
  • 7
  • 25
  • Possible duplicate of https://stackoverflow.com/q/12688717/680068 – zx8754 Feb 18 '20 at 12:31
  • @zx8754 jakob's question was about custom round rules. I'm trying to understand a specifc case. – Alberson Miranda Feb 18 '20 at 12:34
  • This answer from the linked post might explain the problem: https://stackoverflow.com/a/39913257/680068 Try this example: `round(seq(1:10) + 0.445, 2)` – zx8754 Feb 18 '20 at 12:35
  • @zx8754 that resulted in .44 when integers are 2 and 3, and .45 when else. I don't get the logic in that. Couldn't find it in that answer aswell. Did you figure that out? – Alberson Miranda Feb 18 '20 at 12:49

1 Answers1

4

The double numbers are not represented exactly and round uses the represented number.

sprintf("%.20f", 45.445)
#[1] "45.44500000000000028422"
sprintf("%.20f", 73.445)
#[1] "73.44499999999999317879"
GKi
  • 37,245
  • 2
  • 26
  • 48
  • Oh, i get it now! Since 5 isn't the last number or it's not followed by zeroes, R doesn't apply the round to even rule. Is that right? – Alberson Miranda Feb 18 '20 at 13:17
  • Yes. Round does not get `45.445` it gets `sprintf("%a", 45.445)` `0x1.6b8f5c28f5c29p+5` or `45.44500000000000028421709430404007434844970703125`. – GKi Feb 18 '20 at 13:32