Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
In Ruby, when you divide two integers (Integer), there will be a result too an integer. Therefore:
6 / 4
returns 1, not 1.5. Ruby just discards the fractional part - it's so-called integer division.
Why does this happen
- 6 and 4 are both class objects Integer.
- Operator /between two integers returns Integer, trimming the decimal part.
6.class # => Integer 4.class # => Integer 6 / 4 # => 1
How to get the correct result with the decimal part
There are several options. Let's consider in turn.
How to get the correct result with the decimal part:
6.0 / 4 # => 1.5 6 / 4.0 # => 1.5
Use the fdiv method. The fdiv method performs division and always returns Float, even if both numbers are integers. This is convenient when exact fractional division is required without an explicit type transformation.
6.fdiv(4) # => 1.5
Explicit type conversion (to_f). The to_f method converts a number to Float. After that, the division is automatically performed as floating-point numbers, and the result will also be Float. You can also convert a divisor.
6.to_f / 4 # => 1.5
In short:Integer division (Integer /Integer) cuts the fractional part.To get a floating point number (Float), you need:
- use Float in division (6.0 / 4)
- or the fdiv method (6.fdiv(4))
Some more examples:
# Integer division p 7 / 2 # => 3 # Sharing with Float p 7.0 / 2 # => 3.5 p 7 / 2.0 # => 3.5 p 7.fdiv(2) # => 3.5 p 7.to_f / 2 # => 3.5
This post doesn't have any additions from the author yet.