低于零时向上舍入而不是向下舍入
Round up instead of down when below zero
似乎Ruby选择将负数向下舍入而不是接近零。
-1.5.round
#=>-2
而正数则相反:
2.5.round
#=>3
如何舍入负数(接近于零)而不是向下舍入?我正在使用 ruby 版本 2.2.2.
这应该有效。
> (-1.5+0.5).floor
=> -1
> (-1.4+0.5).floor
=> -1
> (-1.6+0.5).floor
=> -2
也许您需要根据需要进行一些调整:
def roundy(x)
x.to_i
if x<0
puts (x. + 0.1).round
else puts x.round
end
end
似乎Ruby选择将负数向下舍入而不是接近零。
-1.5.round
#=>-2
而正数则相反:
2.5.round
#=>3
如何舍入负数(接近于零)而不是向下舍入?我正在使用 ruby 版本 2.2.2.
这应该有效。
> (-1.5+0.5).floor
=> -1
> (-1.4+0.5).floor
=> -1
> (-1.6+0.5).floor
=> -2
也许您需要根据需要进行一些调整:
def roundy(x)
x.to_i
if x<0
puts (x. + 0.1).round
else puts x.round
end
end