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 into an int, meaning 2.34.round # => 2.
Is there a simple effect way to do something like 2.3465 # => 2.35
This question is related to
ruby-on-rails
ruby
rounding
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
def rounding(float,precision)
return ((float * 10**precision).round.to_f) / (10**precision)
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
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
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
You can also provide a negative number as an argument to the round
method to round to the nearest multiple of 10, 100 and so on.
# 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
what about (2.3465*100).round()/100.0
?
Source: Stackoverflow.com