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 .round
which basically turns it in
You can add a method in Float Class, I learnt this from 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
If you just need to display it, I would use the number_with_precision helper.
If you need it somewhere else I would use, as Steve Weet pointed, the round
method
For ruby 1.8.7 you could add the following to your code:
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
Pass an argument to round containing the number of decimal places to round to
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
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
def rounding(float,precision)
return ((float * 10**precision).round.to_f) / (10**precision)
end