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

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

例子:

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

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

我正在运行Ruby 1.8.7。

这一般起作用:

 ceil(number*10)/10 

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

 (number*10).ceil/10.0 

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

 10.38.round(1) # => 10.4 

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

如果您有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 

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

(number/10.0).ceil*10

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