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

前端 未结 7 2091
悲哀的现实
悲哀的现实 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:40

    You can check it with irb:

    $ irb
    >> 2 / 3
    => 0
    >> 2.to_f / 3
    => 0.666666666666667
    >> 2 / 3.to_f
    => 0.666666666666667
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 14:54

    Change the 5 to 5.0. You're getting integer division.

    0 讨论(0)
  • 2020-11-22 14:56

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

    9.fdiv(5)  #=> 1.8
    
    0 讨论(0)
  • 2020-11-22 15:01

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

    9.0 / 5  #=> 1.8
    9 / 5.0  #=> 1.8
    
    0 讨论(0)
  • 2020-11-22 15:01

    Fixnum#to_r is not mentioned here, it was introduced since ruby 1.9. It converts Fixnum into rational form. Below are examples of its uses. This also can give exact division as long as all the numbers used are Fixnum.

     a = 1.to_r  #=> (1/1) 
     a = 10.to_r #=> (10/1) 
     a = a / 3   #=> (10/3) 
     a = a * 3   #=> (10/1) 
     a.to_f      #=> 10.0
    

    Example where a float operated on a rational number coverts the result to float.

    a = 5.to_r   #=> (5/1) 
    a = a * 5.0  #=> 25.0 
    
    0 讨论(0)
提交回复
热议问题