Round up from .5

前端 未结 7 826
一个人的身影
一个人的身影 2020-11-22 11:41

Yes I know why we always round to the nearest even number if we are in the exact middle (i.e. 2.5 becomes 2) of two numbers. But when I want to evaluate data for some peopl

7条回答
  •  暖寄归人
    2020-11-22 11:48

    This method:

    round2 = function(x, n) {
      posneg = sign(x)
      z = abs(x)*10^n
      z = z + 0.5
      z = trunc(z)
      z = z/10^n
      z*posneg
    }
    

    does not seem to work well when we have numbers with many digits. E.g. doing round2(2436.845, 2) will give us 2436.84. The issue seems to occur with the trunc(z) function.

    Overall, I think it has something to do with the way R stores numbers and thus the trunc and float function doesn't always work. I was able to get around it in not the most elegant way:

    round2 = function(x, n) {
      posneg = sign(x)
      z = abs(x)*10^n
      z = z + 0.5
      z = trunc(as.numeric(as.character(z)))
      z = z/10^n
      (z)*posneg
    }
    

提交回复
热议问题