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

RubyMathFloating PointDivisionInteger Division

Ruby Problem Overview


For example:

9 / 5  #=> 1

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

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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

Solution 3 - Ruby

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

9.fdiv(5)  #=> 1.8

Solution 4 - Ruby

You can check it with irb:

$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667

Solution 5 - Ruby

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.

Solution 6 - Ruby

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

Solution 7 - Ruby

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 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErwinMView Question on Stackoverflow
Solution 1 - Rubymu is too shortView Answer on Stackoverflow
Solution 2 - RubyveesView Answer on Stackoverflow
Solution 3 - RubyKonrad ReicheView Answer on Stackoverflow
Solution 4 - RubyRenaudView Answer on Stackoverflow
Solution 5 - RubyRok KraljView Answer on Stackoverflow
Solution 6 - RubyTyler EavesView Answer on Stackoverflow
Solution 7 - RubyucpuzzView Answer on Stackoverflow