Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a float to the nearest integer in ruby

Tags:

ruby

If i have a float of 49.967 and I do .to_i it will chop it down to 49 which for my use of disk space analysis .967 is over 900mb of space that wont be accounted for in the displays.

Is there a function to round numbers to the nearest integer or would i have to define it my self like this:

class Float
  def to_nearest_i
    (self+0.5).to_i
  end
end

so that i could then do:

>> 5.44.to_nearest_i
=> 5
>> 5.54.to_nearest_i
=> 6
like image 910
Arcath Avatar asked Dec 03 '10 13:12

Arcath


People also ask

How do you round a float to an int?

Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.

How do you round an integer 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 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.

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

Try Float.round.

irb(main):001:0> 5.44.round => 5 irb(main):002:0> 5.54.round => 6 
like image 164
detunized Avatar answered Sep 21 '22 23:09

detunized