0

How does R round numbers with the round() function? For example:

round(0.345, 2)
# [1] 0.34

I would expect 0.35.

round(0.3455, 3)
# [1] 0.346

This is what's expected.

rawr
  • 20,481
  • 4
  • 44
  • 78
jhvdz
  • 186
  • 6
  • 3
    this is in the documentation `?round`: `Note that for rounding off a 5, the IEC 60559 standard is expected to be used, ‘go to the even digit’. Therefore round(0.5) is 0 and round(-1.5) is -2.` – rawr Apr 03 '16 at 20:08
  • see also e.g. http://stackoverflow.com/questions/34845236/round-but-5-should-be-floored – Ben Bolker Apr 03 '16 at 20:10
  • @rawr, post as answer (I don't see an exact dupe) ? – Ben Bolker Apr 03 '16 at 20:10

1 Answers1

0

One hack to that function I've used before to get what you expect out of it... If the number has 5 decimal accuracy, multiply by your desired # of decimals to round off (I.e. *1000), call as.integer() on the result, then multiply by 0.001. A simple function follows this psuedo code:

Make your own function with an input for the # of decimals desired. Multiply the input value by 10^(# decimals input). Do an as.integer() on this value. Now multiply by 10^(-# decimals input). Return this value.

Matt
  • 2,602
  • 13
  • 36