R change decimal place without round off

2020-03-31 23:34发布

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

I'd like to have 1.8

2条回答
Deceive 欺骗
2楼-- · 2020-04-01 00:12

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
查看更多
男人必须洒脱
3楼-- · 2020-04-01 00:13
> 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.

查看更多
登录 后发表回答