Round up from .5

前端 未结 7 793
一个人的身影
一个人的身影 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 12:15

    This appears to work:

    rnd <- function(x) trunc(x+sign(x)*0.5)
    

    Ananda Mahto's response seems to do this and more - I am not sure what the extra code in his response is accounting for; or, in other words, I can't figure out how to break the rnd() function defined above.

    Example:

    seq(-2, 2, by=0.5)
    #  [1] -2.0 -1.5 -1.0 -0.5  0.0  0.5  1.0  1.5  2.0
    round(x)
    #  [1] -2 -2 -1  0  0  0  1  2  2
    rnd(x)
    #  [1] -2 -2 -1 -1  0  1  1  2  2
    

提交回复
热议问题