Tracks
/
Ruby
Ruby
/
Syllabus
/
Floating Point Numbers
Fl

Floating Point Numbers in Ruby

5 exercises

About Floating Point Numbers

A floating-point number is a number with zero or more digits behind the decimal separator. Examples are 4.0, 0.1, 3.14, -6.4 16.984025 and 1024.0. In Ruby, floating-point numbers are implemented through the Float class.

You can find a short introduction to floating-point numbers at 0.30000000000000004.com.

The Float Toy page has a nice, graphical explanation how a floating-point numbers' bits are converted to an actual floating-point value.

To repeatedly execute logic, one can use loops. In this example the while loop is useful because it keeps on looping while a condition evaluates to some truthy value (i.e. not false or nil). Ruby implements a loop similar to the while loop. It's called the until loop, and you've probably guessed what it does. It keeps looping until a boolean condition evaluates to true. In some languages, to make a piece of code execute an unlimited number of times, constructs like while true are used. In Ruby, the loop loop exists for that purpose. Even though the loop loop does not depend on a single condition, it can be canceled by using a return or break keyword.

The #years_before_desired_balance method from the previous exercise could have been written by using any of the three mentioned loops:

while

def self.years_before_desired_balance(current_balance, desired_balance)
  years = 0
  while current_balance < desired_balance
    current_balance = annual_balance_update(current_balance)
    years += 1
  end
  years
end

until

def self.years_before_desired_balance(current_balance, desired_balance)
  years = 0
  until current_balance >= desired_balance
    current_balance = annual_balance_update(current_balance)
    years += 1
  end
  years
end

loop

def self.years_before_desired_balance(current_balance, desired_balance)
  years = 0
  loop do
    current_balance = annual_balance_update(current_balance)
    years += 1
    return years if current_balance >= desired_balance
  end
end

As you have probably noticed, Ruby has no increment operator (i++) like some other languages do. Instead, constructs like i += 1 (which is equal to i = i + 1) can be used.

Edit via GitHub The link opens in a new window or tab

Learn Floating Point Numbers

Practicing is locked

Unlock 4 more exercises to practice Floating Point Numbers