四舍五入到最近的十分之一?

时间:2011-08-29 16:55:28

标签: ruby math rounding

我需要四舍五入到最接近的十分之一。我需要的是ceil,但精确到小数点后第一位。

示例:

10.38 would be 10.4
10.31 would be 10.4
10.4 would be 10.4

因此,如果它是过去十分之一的任何数量,那么它应该被四舍五入。

我正在运行Ruby 1.8.7。

5 个答案:

答案 0 :(得分:28)

这一般起作用:

ceil(number*10)/10

所以在Ruby中应该是这样的:

(number*10).ceil/10.0

答案 1 :(得分:6)

Ruby的圆方法可以消耗精度:

10.38.round(1) # => 10.4

在这种情况下,1会让你四舍五入到最接近的十分之一。

答案 2 :(得分:3)

如果您有ActiveSupport,它会添加一个圆形方法:

3.14.round(1) # => 3.1
3.14159.round(3) # => 3.142

来源如下:

def round_with_precision(precision = nil)
  precision.nil? ? round_without_precision : (self * (10 ** precision)).round / (10 ** precision).to_f
end

答案 3 :(得分:2)

在Ruby中你可以做到最接近的十分之一

(number/10.0).ceil*10

(12345/10.0).ceil*10#=> 12350

答案 4 :(得分:0)

(10.33  + 0.05).round(1) # => 10.4

这总是像 ceil 那样四舍五入,简洁明了,支持精度,并且没有傻瓜/ 10 * 10.0的东西。

例如。四舍五入到最接近的百分之一:

(10.333  + 0.005).round(2) # => 10.34

精确到千分之一:

(10.3333  + 0.0005).round(3) # => 10.334