2010-01-13 107 views
125

我遇到了舍入問題。我有一個浮點數,我想四捨五入到十進制的百分之一。但是,我只能用.round基本上把它變成一個int,這意味着2.34.round # => 2.有一個簡單的有效途徑做這樣2.3465 # => 2.35Ruby中的舍入浮點數

+1

'2.3465.round(2)=> 2.35' – Magne 2017-09-08 13:03:41

回答

159

東西顯示時,您可以使用(例如)

>> '%.2f' % 2.3465 
=> "2.35" 

如果你可以用它來存放圓形的,你可以用

>> (2.3465*100).round/100.0 
=> 2.35 
+0

偉大的回答謝謝,我知道有一個簡單的方法它。 – user211662 2010-01-13 03:45:55

+2

謝謝。我沒有意識到sprintf會爲我四捨五入。 'sprintf'%.2f',2.3465'也適用。 – 2012-04-07 17:01:11

+46

value.round(2)比這個解決方案更好 – 2013-12-05 03:22:21

358

參數傳遞到輪含小數的數字四捨五入到

>> 2.3465.round 
=> 2 
>> 2.3465.round(2) 
=> 2.35 
>> 2.3465.round(3) 
=> 2.347 
+7

這似乎比乘法,舍入和除法更明智。 +1 – 2010-01-13 11:41:52

+3

嗯,這個方法似乎沒有在紅寶石1.8.7。也許在1.9? – 2011-02-27 00:40:52

+2

@布萊恩。這絕對是1.9,也是在軌道上(這個問題被標記) – 2011-02-28 00:09:16

6

您可以Float類添加了一個方法,我學會了這從計算器:

class Float 
    def precision(p) 
     # Make sure the precision level is actually an integer and > 0 
     raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0 
     # Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0 
     return self.round if p == 0 
     # Standard case 
     return (self * 10**p).round.to_f/10**p 
    end 
end 
3
def rounding(float,precision) 
    return ((float * 10**precision).round.to_f)/(10**precision) 
end 
0

對於紅寶石1.8.7,你可以添加以下代碼:

class Float 
    alias oldround:round 
    def round(precision = nil) 
     if precision.nil? 
      return self 
     else 
      return ((self * 10**precision).oldround.to_f)/(10**precision) 
     end 
    end 
end 
1

如果你只是需要顯示它,我會使用number_with_precision幫手。 如果你需要在其他地方我會用,因爲史蒂夫Weet指出,該round方法

+1

請注意,'number_with_precision'是Rails-only方法。 – Smar 2015-07-15 11:39:43

3

您也可以到round方法提供一個負數作爲參數舍入到10的最接近倍數,100等。

# Round to the nearest multiple of 10. 
12.3453.round(-1)  # Output: 10 

# Round to the nearest multiple of 100. 
124.3453.round(-2)  # Output: 100 
5

您可以使用此四捨五入到精密度..

//to_f is for float 

salary= 2921.9121 
puts salary.to_f.round(2) // to 2 decimal place     

puts salary.to_f.round() // to 3 decimal place