Truncate decimal to specified places

后端 未结 3 414
慢半拍i
慢半拍i 2020-12-16 18:11

This seems like it should be a fairly easy problem to solve but I am having some trouble locating an answer.

I have a vector which contains long decimals and I want

3条回答
  •  抹茶落季
    2020-12-16 18:40

    trunc(x*10^4)/10^4
    

    yields 0.1234 like expected.

    More generally,

    trunc <- function(x, ..., prec = 0) base::trunc(x * 10^prec, ...) / 10^prec;
    print(trunc(0.123456789, prec = 4) # 0.1234
    print(trunc(14035, prec = -2), # 14000
    

提交回复
热议问题