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 floatFloat#ceil: Round up to the nearest integerFloat#floor: Round down to the nearest integerFloat#round: Round to the nearest integerFloat#to_i: Truncate to the nearest integerWhat'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
floor (without arguments) returns the next integer less than or equal to the receiverceil (without arguments) returns the next integer greater than or equal to the receiverto_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).
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