Why is division in Ruby returning an integer instead of decimal value? Why is division in Ruby returning an integer instead of decimal value? ruby ruby

Why is division in Ruby returning an integer instead of decimal value?


It’s doing integer division. You can use to_f to force things into floating-point mode:

9.to_f / 5  #=> 1.89 / 5.to_f  #=> 1.8

This also works if your values are variables instead of literals. Converting one value to a float is sufficient to coerce the whole expression to floating point arithmetic.


It’s doing integer division. You can make one of the numbers a Float by adding .0:

9.0 / 5  #=> 1.89 / 5.0  #=> 1.8


There is also the Numeric#fdiv method which you can use instead:

9.fdiv(5)  #=> 1.8