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

前端 未结 7 2185
悲哀的现实
悲哀的现实 2020-11-22 14:13

For example:

9 / 5  #=> 1

but I expected 1.8. How can I get the correct decimal (non-integer) result? Why is it returning <

7条回答
  •  一整个雨季
    2020-11-22 14:47

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

    9.to_f / 5  #=> 1.8
    9 / 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.

提交回复
热议问题