Ruby - Floating Point Numbers


You ran a test where you divided 10 by 3, like so:

puts 10 / 3 # return 3 

The result is 3, although the actual answer should be 3.33 recurring.

By default, Ruby considers any numbers without a floating point to be an integer.

When you say 10 / 3, you're asking Ruby to divide two integers, and Ruby gives you an integer as a result.

Let's refine the code slightly:

puts 10.0 / 3.0  #3.33333333333 

Now you get the desired result.

Ruby is now working with number objects of the Float class, and returns a Float, giving you the level of precision you'd expect.

Convert integer to floating point numbers


x = 10 
y = 3 
puts x.to_f / y.to_f


When reaching the division, both x and y are converted to their floating point number equivalents using the Integer class's to_f method.

Floating point numbers can be converted back in the other direction, to integers, using to_i:

puts 5.7.to_i # 5