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
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.
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.
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.
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.
Try Float.round
.
irb(main):001:0> 5.44.round => 5 irb(main):002:0> 5.54.round => 6
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