1

I don't understand and help also doesn't say anything about round depending on digits:

a <- 22.899999999999999
# [1] 22.899999999999999
options(digits = 20)
round(a, 1)
# [1] 22.899999999999999
options(digits = 7)
round(a, 1)
# [1] 22.9
options(digits = 20)
round(a, 1)
# [1] 22.899999999999999
Christoph
  • 6,841
  • 4
  • 37
  • 89
MichiSmith
  • 317
  • 1
  • 7
  • 1
    related: https://stackoverflow.com/questions/588004/is-floating-point-math-broken 22.9 is not an exact double, because computer arithmetic uses the base 16 and not the base 10 – jogo Aug 20 '18 at 12:53
  • @jogo But why is the output of round() affected by the number representation? "0.3" is known to the R-console. – MichiSmith Aug 20 '18 at 13:03
  • For 0.3 the distance to the next computer number is sufficient small. (also 0.3 can not be an exact double in base 16). – jogo Aug 20 '18 at 13:05
  • Correction to my two other comments: R is using computer numbers with base 2, see `.Machine` for details. related: https://en.wikipedia.org/wiki/Double-precision_floating-point_format – jogo Aug 21 '18 at 06:40

1 Answers1

2

It doesn't, round just returns your original number in this case.

identical(a,round(a,1))
[1] TRUE

Changing digits in options affects how such numbers are displayed.

James
  • 65,548
  • 14
  • 155
  • 193
  • So `round` does not care about how output will be displayed - it is kind of a "mathematical function". If you expect output to look like expected you need `formatC(a, 1)` giving "0.3"? – Christoph Aug 20 '18 at 13:30
  • It is limited by floating point arithmetic. Your number `a` and `22.9` map to the same floating point number. Use `as.character` if you want a string representation which will do some appropriate rounding, or `format` for more control. – James Aug 20 '18 at 13:59
  • I really never expected `as.character(round(a, 1))` to be "22.9"! You should add those examples in your answer. Too me this is really not obvious... – Christoph Aug 20 '18 at 14:30