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

前端 未结 7 2092
悲哀的现实
悲哀的现实 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 15:02

    You can include the ruby mathn module.

    require 'mathn'
    

    This way, you are going to be able to make the division normally.

    1/2              #=> (1/2)
    (1/2) ** 3       #=> (1/8)
    1/3*3            #=> 1
    Math.sin(1/2)    #=> 0.479425538604203
    

    This way, you get exact division (class Rational) until you decide to apply an operation that cannot be expressed as a rational, for example Math.sin.

    0 讨论(0)
提交回复
热议问题