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?
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With