R change decimal place without round off

2020-04-01 00:12发布

问题:

> signif(1.89,digits=2)
[1] 1.9

I'd like to have 1.8

回答1:

This is a bit clunky, but it will work and keep everything numeric:

x <- 1.829380

trunc.dec <- function(x,n) {
  floor(x*10^n)/10^n
}

Result:

trunc.dec(x,1)
#[1] 1.8
trunc.dec(x,2)
#[1] 1.82
trunc.dec(x,3)
#[1] 1.829
trunc.dec(x,4)
#[1] 1.8293


回答2:

> format(round(1.20, 2), nsmall = 2)
[1] "1.20"
> format(round(1, 2), nsmall = 2)
[1] "1.00"
> format(round(1.1234, 2), nsmall = 2)
[1] "1.12"

try this variation from this article so you can have more samples.