Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better Ruby implementation of round decimal to nearest 0.5

Tags:

This seems horrible inefficient. Can someone give me a better Ruby way.

def round_value   x = (self.value*10).round/10.0 # rounds to two decimal places   r = x.modulo(x.floor) # finds remainder   f = x.floor    self.value = case   when r.between?(0, 0.25)     f   when r.between?(0.26, 0.75)     f+0.5   when r.between?(0.76, 0.99)     f+1.0   end end 
like image 313
Steve McKinney Avatar asked Oct 01 '10 07:10

Steve McKinney


People also ask

How do you round decimals in Ruby?

The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter ( round() ) or with a parameter ( round(n) ). n here means the number of decimal places to round it to.

How do you round in Ruby?

Ruby | Numeric round() function The round() is an inbuilt method in Ruby returns a number rounded to a number nearest to the given number with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.

How do you round off a float in Ruby?

Ruby Float round() method with exampleround() is a float class method which return a float value rounded to the nearest value with n digits decimal digits precision.

Does Ruby round up or down?

Ruby Language Numbers Rounding Numbers The round method will round a number up if the first digit after its decimal place is 5 or higher and round down if that digit is 4 or lower.


1 Answers

class Float   def round_point5     (self * 2).round / 2.0   end end 

A classic problem: this means you're doing integer rounding with a different radix. You can replace '2' with any other number.

like image 115
Peter Avatar answered Oct 09 '22 10:10

Peter