def rounding(float,precision)
return ((float * 10**precision).round.to_f) / (10**precision)
end
3
你可以在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
# 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
2
对于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
0
(2.3465*100).round()/100.0 怎么样?
3
显示时,您可以使用(例如)
>> '%.2f' % 2.3465
=> "2.35"
如果要将其存储为圆形,则可以使用
>> (2.3465*100).round / 100.0
=> 2.35
372
你可以用它来四舍五入..
//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
9 回答
将参数传递给包含要舍入的小数位数的round
你可以在Float类中添加一个方法,我从stackoverflow中学到了这个:
如果你只需要显示它,我会使用number_with_precision助手 . 如果你需要它,我会使用,就像Steve Weet指出的那样,
round
方法您还可以提供负数作为
round
方法的参数,以舍入到最接近的10,100的倍数,依此类推 .对于ruby 1.8.7,您可以在代码中添加以下内容:
(2.3465*100).round()/100.0
怎么样?显示时,您可以使用(例如)
如果要将其存储为圆形,则可以使用
你可以用它来四舍五入..