Integer and float: two kinds of number
Not every number is the same kind of number
5 and 5.0 are the same value in math. In Ruby they're different kinds of object.
5.class # => Integer
5.0.class # => Float
Integer holds exact whole numbers with no decimal point: 5, -12, 1000. Float holds numbers with a decimal point, like 5.0, 3.14 and -0.5, approximating real numbers the way a calculator display does. The literal decides which you get. Type a decimal point and you get a Float; leave it out and you get an Integer.
Why the distinction exists at all
The split reflects how these numbers behave. Items in a cart, a page number or a count of days are exact whole quantities, so Integer fits. A price with cents, an average or a percentage needs fractions, so Float fits. Picking the right one up front avoids the two surprises in the next two lessons: integer division and floating-point imprecision.
Arithmetic mixes naturally
Combine an Integer and a Float and you get a Float. Ruby promotes the narrower type to match the wider one automatically.
5 + 2 # => 7, Integer + Integer = Integer
5 + 2.0 # => 7.0, Integer + Float = Float
5.0 + 2 # => 7.0, Float + Integer = Float, same either order
You never declare the conversion. Ruby works out the result type from the values, the no-ceremony spirit of the Ruby variables & assignment course.
Converting deliberately
Two methods convert explicitly. They're cousins of to_s and to_sym from the last course.
5.to_f # => 5.0, Integer to Float
5.9.to_i # => 5, Float to Integer, the decimal part is simply dropped, not rounded
Note the last one. to_i truncates: it cuts off everything after the decimal point instead of rounding. 5.9.to_i is 5, not 6. Lesson 4 covers round, which rounds.
What this course covers
- Lesson 1, Integer and Float: two kinds of number, and why the distinction matters (you are here)
- Lesson 2, Integer division: the most common numeric surprise in Ruby
- Lesson 3, Float precision: why
0.1 + 0.2doesn't quite equal0.3 - Lesson 4, Numeric methods:
round,abs,even?and other everyday tools - Lesson 5, Boolean values:
trueandfalse, and nothing in between - Lesson 6, Truthiness: what counts as "true enough" inside a condition
- Lesson 7, Putting it together: a small challenge combining numbers and booleans
By the end, you'll know which type a value should be and what happens when the two mix.
Keep going with lesson 2
Integer division: the classic gotcha
Shows why dividing two Integers drops the fraction, how to get a fractional result, and what % returns.
A free account also gives you the quizzes, your progress and notes, and the discussion.