R change decimal place without round off

前端 未结 2 1238
遇见更好的自我
遇见更好的自我 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
    
    0 讨论(0)
  • 2021-01-17 01:31
    > 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.

    0 讨论(0)
提交回复
热议问题