← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 3 of 7

Float Type

A Float is a number with a decimal point, like a measured length. It is for things that are not whole, like 3.14.

In this page:

  1. Float Type
Syntax
ruby
number = 3.14
number.round(2)
number.class    # Float

Float Type

Float represents floating-point (decimal) numbers in Ruby, following standard IEEE 754 double-precision behavior, including the usual floating-point rounding quirks.

Dividing two integers with / gives integer division, so at least one operand must be a Float to get a fractional result. to_f converts a value to a float explicitly.

Note: Divide with 10.0 / 3 (or call .to_f on an operand) to force a fractional result instead of integer division.

Example: Float Type

markup
price = 19.99
puts price.class
puts price * 2

puts 10 / 3          # integer division
puts 10.0 / 3         # float division
puts 10.to_f / 3
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Comparing floats with ==, as in 0.1 + 0.2 == 0.3, which is false; compare with a tolerance or use round.
  2. Writing 10 / 3 and expecting 3.33, when both operands are integers and the result is 3.
  3. Using Float for money, when rounding errors can add up and BigDecimal or cents in Integer are safer.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.