R change decimal place without round off

心已入冬 提交于 2019-12-01 12:42:46

问题


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



来源:https://stackoverflow.com/questions/24601887/r-change-decimal-place-without-round-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!