0

I tried rounding off :-

  round(9962.3099999999995,2)
   [1] 9962.3099999999995

How to round such numbers with long decimal place resolution?

  • 5
    It Works fine for me. I got 9962.31 – Jilber Urbina Mar 27 '18 at 15:53
  • is it related to options() command? Because i don't know what difference do we have...i am still getting the same number – Abhay Saini Mar 27 '18 at 16:00
  • 3
    I cannot replicate this error. Maybe check `options("digits")`. But also note there's a different between rounding a number and formatting it so it prints only with a certain number of digits. If this is for display purposes, maybe use a function like `format()` or `sprintf()`. – MrFlick Mar 27 '18 at 16:00
  • 1
    Computers can't represent exact decimals due to floating point precision. Modify your print behavior by setting the `digits` option--- `options(digits = 7)` is the default and works fine in this case---or by coercing to a character string with the number of digits you want using the functions MrFlick recommends. – Gregor Thomas Mar 27 '18 at 16:03
  • i can't limit options because i have GDP data which numbers into billions – Abhay Saini Mar 27 '18 at 16:11
  • 2
    The size of your data is not relevant to the digits option – IceCreamToucan Mar 27 '18 at 16:13
  • 1
    To expand slightly on comments by MrFlick and Gregor, this is related to [R FAQ 7.31](https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f). I can reproduce this behavior with `options(digits=7);round(pi,2);options(digits=17);round(pi,2)`. – r2evans Mar 27 '18 at 16:35
  • Abhay Saini, setting `options(digits=...)` does *nothing* to the value of the data, it only affects how it is displayed on the screen. Note that with `options(digits=1);pi;pi*100`, the value of `pi` is not changing, only what is printed on the console. (I suggest running `options(digits=7)`, the default value, after these examples: setting it to "1" is rarely what is needed/wanted the majority of time.) – r2evans Mar 27 '18 at 16:38
  • okay thanks guys, i realize that this problem is caused by conversion of character to numeric...."34.72" changes to 34.7199999999999999 – Abhay Saini Mar 27 '18 at 17:53
  • That's not really the point... it's not a conversion issue. It's a universal issue with numerics. – Gregor Thomas Mar 27 '18 at 18:09
  • So how do we solve it? Gregor, you do know that digits doesn't solve the question....instead of marking it as duplicate, please avoid the question if you don't know the answer.. – Abhay Saini Mar 27 '18 at 18:19
  • https://stackoverflow.com/questions/49521036/how-can-i-round-off-data-to-mark-it-as-interpolated-or-stale-by-suffixing-in-0-0 – Abhay Saini Mar 27 '18 at 19:36

0 Answers0