A.6 Float

decimals

A.6.1 Math Operations for the Float Class

Standard operations are similar to those for the Integer class. The only exception is the / operator which returns fractional results.

12 / 5     # => 2 
12.0 / 5.0 # => 2.4 
12 / 5.0   # => 2.4  
12.0 / 5   # => 2.` 

A.6.2 ** Float operator

Float ** Float ⇒ Float

The **operator for Floats can additionally be used to calculate roots.

9 ** 0.5     # => 3.0, since 9^(1/2) = sqaureroot of 9  
8 ** (1/3.0) # => 2.0, since 8^(1/3) = cuberoot of 8  

Full explanation

A.6.3 .round

Float#round ⇒ Integer

or

Float#round(Integer) ⇒ Float

  • Returns the whole part (Integer) of a decimal when not given any argument.
  • When given an argument, returns a Float rounded to the number of decimal places specified by the argument.

3.14159.round # => 3
3.14159.round(3) # => 3.142
3.14139.round(3) # => 3.141

Full explanation

A.6.4 .to_i (Float)

Float#to_i ⇒ Integer

Converts a float to an integer by rounding the float down to closest whole number.

Returns an Integer

"8.9".to_i

8

"8.1".to_i

8

A.6.4.1 Integer and Float division examples

12 / 5 # => 2
(12 / 5).to_f # => 2.0
12.to_f / 5 # => 2.4
12 / 5.to_f # => 2.4
(12.0 / 5 ).to_i # => 2
(12 / 5.0).to_i # => 2