此处 round()
的行为符合预期:
round(3.5)
[1] 4
然而,this 令我惊讶:
round(2.5)
[1] 2
当我们希望一切以.5
结尾的向上四舍五入时,R中实现这一目标的最佳实践是什么?
理想情况下,解决方案还应满足小数点后第一位的四舍五入,例如以下应返回 0.2
:
round(0.15, 1)
[1] 0.1
答案 0 :(得分:1)
在谷歌搜索“r 中的商业四舍五入”后,出现了 this 答案,可以将其调整为具有 0 个小数位的默认值,如下所示:
round2 = function(x, decimal_places = 0) {
posneg = sign(x)
z = abs(x)*10^decimal_places
z = z + 0.5 + sqrt(.Machine$double.eps)
z = trunc(z)
z = z/10^decimal_places
z*posneg
}
示例:
round2(3.5)
[1] 4
round2(2.5)
[1] 3
round2(0.15, decimal_places = 1)
[1] 0.2