Ruby 中的舍入浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2054217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rounding float in Ruby
提问by user211662
I'm having problems rounding. I have a float, which I want to round to the hundredth of a decimal. However, I can only use .roundwhich basically turns it into an int, meaning 2.34.round # => 2.Is there a simple effect way to do something like 2.3465 # => 2.35
我在四舍五入时遇到问题。我有一个浮点数,我想四舍五入到小数点的百分之一。但是,我只能使用.round它基本上将其转换为 int,这意味着2.34.round # => 2.是否有一种简单的效果方法可以执行类似的操作2.3465 # => 2.35
回答by Steve Weet
Pass an argument to round containing the number of decimal places to round to
将参数传递给包含要四舍五入的小数位数的 round
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
回答by Peter
When displaying, you can use (for example)
显示时,您可以使用(例如)
>> '%.2f' % 2.3465
=> "2.35"
If you want to store it rounded, you can use
如果你想把它存储成圆形,你可以使用
>> (2.3465*100).round / 100.0
=> 2.35
回答by tech bun
you can use this for rounding to a precison..
您可以使用它来四舍五入到精确度。
//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
回答by Albert Català
You can add a method in Float Class, I learnt this from stackoverflow:
您可以在 Float 类中添加一个方法,我从 stackoverflow 中学到了这一点:
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
回答by BrunoFacca
You can also provide a negative number as an argument to the roundmethod to round to the nearest multiple of 10, 100 and so on.
您还可以提供一个负数作为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
回答by PeteJLeonard
def rounding(float,precision)
return ((float * 10**precision).round.to_f) / (10**precision)
end
回答by thenoviceoof
what about (2.3465*100).round()/100.0?
怎么样(2.3465*100).round()/100.0?
回答by Fer
If you just need to display it, I would use the number_with_precisionhelper.
If you need it somewhere else I would use, as Steve Weet pointed, the roundmethod
如果您只需要显示它,我会使用number_with_precision助手。如果您在其他地方需要它,我会使用,正如 Steve Weet 指出的那样,该round方法
回答by Robert
For ruby 1.8.7 you could add the following to your code:
对于 ruby 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

