Ruby Language Floats and Integers


Example

1/2 #=> 0

Since we are dividing two integers, the result is an integer. To solve this problem, we need to cast at least one of those to Float:

1.0 / 2      #=> 0.5
1.to_f / 2   #=> 0.5
1 / Float(2) #=> 0.5

Alternatively, fdiv may be used to return the floating point result of division without explicitly casting either operand:

1.fdiv 2 # => 0.5