R change decimal place without round off

前端 未结 2 1236
遇见更好的自我
遇见更好的自我 2021-01-17 00:48
> signif(1.89,digits=2)
[1] 1.9

I\'d like to have 1.8

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 01:26

    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
    

提交回复
热议问题