Ruby Language Casting (type conversion) Floats and Integers

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Ruby Language Question?