Wipster - 9 months ago 70

R Question

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.

Answer

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
```

Source (Stackoverflow)