Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Float#floor and Float#to_i in Ruby?

I'm learning Ruby, and I'm currently in numbers. So as I understand it, there are five ways (perhaps more) to coerce integers and floats to each other:

  • Integer#to_f: Coerce to a new float
  • Float#ceil: Round up to the nearest integer
  • Float#floor: Round down to the nearest integer
  • Float#round: Round to the nearest integer
  • Float#to_i: Truncate to the nearest integer

What's the difference between "rounding down" and "truncating" to the nearest integer?

When I tested it...

puts 34.4.to_i()
puts 34.4.floor()

... it resulted in the same values:

34
34
like image 667
Safwan Samsudeen Avatar asked Dec 13 '25 11:12

Safwan Samsudeen


1 Answers

  • floor (without arguments) returns the next integer less than or equal to the receiver
  • ceil (without arguments) returns the next integer greater than or equal to the receiver
  • to_i discards the fractional part of the receiver and returns the integer part
f f.to_i f.floor f.ceil f.round
11.8 11 11 12 12
11.5 11 11 12 12
11.2 11 11 12 11
11.0 11 11 11 11
-11.2 -11 -12 -11 -11
-11.5 -11 -12 -11 -12
-11.8 -11 -12 -11 -12

to_i behaves like floor for positive numbers and like ceil for negative numbers.

In fact, that's actually how Float#to_i is implemented in numeric.c:

static VALUE
flo_to_i(VALUE num)
{
    double f = RFLOAT_VALUE(num);

    if (f > 0.0) f = floor(f);
    if (f < 0.0) f = ceil(f);

    return dbl2ival(f);
}

There's also truncate which behaves like to_i but takes an optional number of digits (like floor, ceil, and round).

like image 83
Stefan Avatar answered Dec 15 '25 12:12

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!