Reputation: 1570
How can I cut the decimals of a quotient in R? I'm computing millions of values and write them in a file on the fly. To save some space I don't want more than five decimals and also omit trailing zeros.
I tried
options(digits=5)
which I read only is a suggestion to R and doesn't work quit well. And
format(x, nsmall = 5)
determines only the minimum number of decimals. And
sprintf("%.5f", x)
will give me exactly five decimals.
Upvotes: 1
Views: 2138
Reputation:
The round function works just fine if you refrain from changing the digits option beforehand.
Run with the default options:
> round(x = 1.23456777, digits = 5)
[1] 1.23457
Run with changed options:
> options(digits=5)
> round(x = 1.23456777, digits = 5)
[1] 1.2346
Upvotes: 1
Reputation: 23101
How about with just
round(x,5)
x=1.23456777
round(x,5)
#[1] 1.23457
x=1.230000
#round(x,5)
[1] 1.23
If you don't want rounding try this:
as.integer(x*10^5)/10^5
x=1.234567777
as.integer(x*10^5)/10^5
#[1] 1.23456
x=1.230000
as.integer(x*10^5)/10^5
#[1] 1.23
Upvotes: 3