Floats and Integers

Download ruby eBook

Example

1/2 #=> 0

Since we are dividing two integers, the result is an integer. To solve this problem, we need to cast at least one of those to Float:

1.0 / 2      #=> 0.5
1.to_f / 2   #=> 0.5
1 / Float(2) #=> 0.5

Alternatively, fdiv may be used to return the floating point result of division without explicitly casting either operand:

1.fdiv 2 # => 0.5

Stats

Contributors: 3
2016-06-08
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook