Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to closest integer or closest .5 in Ruby

Tags:

rounding

ruby

Maybe the title is confusing, but I will try to explain with examples:

Given a float with precision = 2, I want to be able to round either to its closes integer, or to its closest .5. Examples:

Given: 4.12 --> 4
       4.24 --> 4
       4.25 --> 4.5
       4.33 --> 4.5
       4.53 --> 4.5 
       4.65 --> 4.5 
       4.75 --> 5
       4.84 --> 5

What would be a good way to do this in Ruby?

like image 344
Hommer Smith Avatar asked Jul 27 '12 02:07

Hommer Smith


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 a float to 2 decimal places in Ruby?

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.


1 Answers

Multiply by 2, round, divide by 2.

[4.12, 4.24, 4.25, 4.33, 4.53, 4.65, 4.75, 4.84].map do |x|
  r = (x * 2).round / 2.0
  r.to_i == r ? r.to_i : r
end

=> [4, 4, 4.5, 4.5, 4.5, 4.5, 5, 5]
like image 148
Gary G Avatar answered Nov 15 '22 22:11

Gary G