2009-08-28 28 views

回答

20

检查此链接,我认为这是你需要的。 Ruby rounding

class Float 
    def round_to(x) 
    (self * 10**x).round.to_f/10**x 
    end 

    def ceil_to(x) 
    (self * 10**x).ceil.to_f/10**x 
    end 

    def floor_to(x) 
    (self * 10**x).floor.to_f/10**x 
    end 
end 
+0

感谢您的链接!这些方法完美地工作。 – dotty 2009-08-28 10:54:45

+8

尼斯链接。尽管如此,答案会更好,因此它可以独立存在,尤其是因为链接的代码不完全符合OP要求的内容,即四舍五入到最接近的0.05,但会舍入到特定的小数位。 – tvanfosson 2009-08-28 11:00:51

+3

更糟糕的是,这篇文章实际上是重新实现了内置的ruby函数(小数位数),这是一个坏主意。 – Rob 2012-04-05 14:32:46

21
[2.36363636363636, 4.567563, 1.23456646544846, 10.5857447736].map do |x| 
    (x*20).round/20.0 
end 
#=> [2.35, 4.55, 1.25, 10.6] 
+0

该死,你击败了我几秒钟!我的+1,尽管我心中略有不同的版本。 – Swanand 2009-08-28 10:58:00

+0

根据OP的要求,这不会收集到最接近的0.05,2.36 ....应该是2.40,而不是2.35。 – 2012-04-08 23:40:03

+1

@ChristopherMaujean确实,但(尽管标题)这不是OP所要求的。问题的正文说:“将这些数字上升(**或下降**)至**最接近的** 0.05”。无论如何,如果你想收起来,使用'ceil'而不是'round'。 – sepp2k 2012-04-09 12:34:14

18

一般而言,算法“舍入到最接近的X”是:

round(x/precision)) * precision 

有时最好通过1/precision相乘,因为它是一个整数(且因此它工作得更快一些):

round(x * (1/precision))/(1/precision) 

在你的情况,这将是:

round(x * (1/0.05))/(1/0.05) 

这将计算为:

round(x * 20)/20; 

我不知道任何的Python,不过,这样的语法可能不正确的,但我敢肯定,你可以弄明白。

+1

为了使小数除以20.0 - > round(x * 20)/ 20.0; – Irukandji 2009-11-30 10:43:31

+3

对于ruby:'(7.125 * 20).round/20.0 => 7.15' – 2012-03-23 19:14:39

8

这里的舍入任何给定步长值一般功能:

发生在lib目录下:

lib/rounding.rb 
class Numeric 
    # round a given number to the nearest step 
    def round_by(increment) 
    (self/increment).round * increment 
    end 
end 

和规范:

require 'rounding' 
describe 'nearest increment by 0.5' do 
    {0=>0.0,0.5=>0.5,0.60=>0.5,0.75=>1.0, 1.0=>1.0, 1.25=>1.5, 1.5=>1.5}.each_pair do |val, rounded_val| 
    it "#{val}.round_by(0.5) ==#{rounded_val}" do val.round_by(0.5).should == rounded_val end 
    end 
end 

与用法:

require 'rounding' 
2.36363636363636.round_by(0.05) 

hth。

11

不太精确,但这种方法是大多数人都在谷歌上搜索这个页面

(5.65235534).round(2) 
#=> 5.65 
+1

5.6355.round(2)!= 5.65,但TS想要5.65 – 2013-04-11 05:14:50

+0

此解决方案只将数字四舍五入到小数点后两位,它不返回根据要求舍入到最接近的0.05。 – 2013-05-02 02:01:49

+0

在某些方面你是对的,我应该删除这个答案。但在另一层面上,这是一个非常受欢迎的问题,在人们发现这个答案很有帮助的搜索中被链接到,所以我要保持它可见 – 2014-07-05 14:45:22

4

有可能与String类的%法圆号码。

例如

"%.2f" % 5.555555555 

会给"5.56"作为结果(字符串)。

3

红宝石2现在有一个圆形的功能:

# Ruby 2.3 
(2.5).round 
3 

# Ruby 2.4 
(2.5).round 
2 

也有红宝石2.4选项,如::even:up:down e。G;

(4.5).round(half: :up) 
5