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), the result will also be an integer. Therefore:
6 / 4
returns 1, not 1.5. Ruby simply truncates the fractional part - this is called integer division.
Why this happens
- 6 and 4 are both objects of class Integer.
- The / operator between two integers returns Integer, cutting off the decimal part.
6.class # => Integer 4.class # => Integer 6 / 4 # => 1
How to get the correct result with a decimal part
There are several options. Let's consider them one by one.
How to get the correct result with a 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 you need precise fractional division without explicit type conversion.
6.fdiv(4) # => 1.5
Explicit type conversion (to_f). The to_f method converts a number to Float. After that, division is automatically performed as with floating-point numbers, and the result will also be Float. You can also convert the divisor.
6.to_f / 4 # => 1.5
In short:Integer division (Integer / Integer) truncates the fractional part.To get a floating-point number (Float), you need to:
- use Float in the division (6.0 / 4)
- or the fdiv method (6.fdiv(4))
Here are a few more examples:
# Integer division p 7 / 2 # => 3 # Division 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.