Reputation: 191
I need a R function that always returns same number of digits after the decimal point regardless of how big the argument is. I tried round() but it does not work this way. Here is my example:
Rweb:> round(111234.678912,4) # expect 111234.6789
[1] 111234.7
Rweb:> round(111234.678912/10,4) # expect 11123.4679
[1] 11123.47
Rweb:> round(111234.678912/100,4) # expect 1112.3468
[1] 1112.347
Rweb:> round(111234.678912/1000,4)
[1] 111.2347
Rweb:> round(111234.678912/10000,4)
[1] 11.1235
It does work if the argument is in exponential format but I need work with numbers in floating format.
Upvotes: 18
Views: 8221
Reputation: 1351
let x is a number with big decimal places.
x<-1111111234.6547389758965789345
Here x is a number with big decimal places , you can format decimal places as your wish. Such that we wish to take up to 8 decimal places of this number.
x<-c(1111111234.6547389758965789345)
y<-formatC(x,digits=8,format="f")
[1] "1111111234.65473890"
Here format="f" gives number in the usual decimal places say, xxx.xxx. But if you wanted to get a integer number from this object x you use format="d"
Upvotes: 3
Reputation: 4765
About "bignums", @Carl Witthoft: Thanks, Carl. ... I did think about bignums, when I read it. Are you sure there 's a problem with the rounding? See this:
> mpfr("1.2345456789", prec=84)
1 'mpfr' number of precision 84 bits
[1] 1.23454567889999999999999999
and note that Rmpfr (I'm the maintainer) does stay close to the underlying MPFR library. For round()
, I've applied the logic/principle of f(x) returning a result with the same formal precision as x. If you want rounding with decreased formal precision, you can conveniently use roundMpfr()
:
> roundMpfr(bfoo, 32)
1 'mpfr' number of precision 32 bits
[1] 1.2345456788
Upvotes: 0
Reputation: 21502
For anyone else who, like me, thought the question was going to be about bignums :-), there's this to ponder :-)
Rgames> bfoo<-mpfr("1.234545678909887665453421")
Rgames> bfoo
1 'mpfr' number of precision 84 bits
[1] 1.234545678909887665453421
Rgames> round(bfoo,10)
1 'mpfr' number of precision 84 bits
[1] 1.23454567889999999999999999`
Upvotes: 2
Reputation: 78600
It does round the number to the correct number of digits. However, R has limits on the number of digits it displays of very large numbers. That is- those digits are there, they just aren't shown.
You can see this like so:
> round(111234.678912,4)
[1] 111234.7
> round(111234.678912,4) - 111234
[1] 0.6789
You can use formatC
to display it with any desired number of digits:
> n = round(111234.678912,4)
> formatC(n, format="f")
[1] "111234.6789"
> formatC(n, format="f", digits=2)
[1] "111234.68"
As @mnel helpfully points out, you can also set the number of digits shown (including those to the left of the decimal point) using options
:
> options(digits=6)
> round(111234.678912,4)
[1] 111235
> options(digits=10)
> round(111234.678912,4)
[1] 111234.6789
Upvotes: 18