Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Data Types  ›  Lesson

Integers and Floats

Integers 12 minInteger arithmetic stays whole and division drops the remainder, while any float in a calculation makes the result a float, which is approximate.

Integers and Floats

Bean Cart sold 7 lattes and wants to split the tips between 2 baristas. You type 7 / 2 and Ruby says 3. Where did the half go? Ruby has two main kinds of number, and which one you start with decides what kind of answer you get.

The rule

Integers stay whole; one float in the sum makes a float.

An Integer is a whole number: 12, -3, 0. Ruby integers have no size limit, so 2 ** 100 just works. Underscores make long ones readable: 1_000_000 is one million.

A Float is a number with a decimal point: 4.5, 0.05, -2.0. You must write a digit on both sides of the point: 0.5, not .5.

The rule that trips everyone up: when both numbers are integers, division gives an integer and throws the remainder away. If either is a float, the result is a float:

7 / 2      # => 3     (integer division)
7 % 2      # => 1     (the remainder that was dropped)
7 / 2.0    # => 3.5
7.0 / 2    # => 3.5
7.fdiv(2)  # => 3.5   (float division on purpose)
3 + 1.5    # => 4.5

Integer division rounds down, toward negative infinity, not toward zero. So -7 / 2 is -4, not -3.

Floats are stored in binary, so some decimals cannot be represented exactly:

0.1 + 0.2        # => 0.30000000000000004
(0.1 + 0.2).round(2)  # => 0.3

That is fine for measurements, but money needs care: count in whole cents with integers (450 cents), or use the BigDecimal library.

Numbers are objects, so they come with handy methods:

4.49.round    # => 4
4.5.ceil      # => 5
4.9.floor     # => 4
10.even?      # => true
-3.abs        # => 3

The shortcut

Before you calculate, scan the numbers for a decimal point. No point anywhere: the answer is a whole number, and any division drops the remainder. A point anywhere: the answer is a float.

Splitting Bean Cart tipsStep 1 of 4
  1. The problem

    Tips total 25 dollars, shared by 2 baristas. You write 25 / 2.

Drills

Answer fast — trust the rule.

quick drill

What is 9 / 4 in Ruby?

quick drill

What is 9 / 4.0?

quick drill

What is 17 % 5?

quick drill

What does 0.1 + 0.2 == 0.3 return?

quick drill

What is -7 / 2?

Remember

  • Integers stay whole; one float in the sum makes a float.
  • Scan for a decimal point before you divide.
  • Trap: 7 / 2 is 3, and floats are approximate, so handle money in whole cents or BigDecimal.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhere did the half go?

Bean Cart splits 25 dollars of tips between 2 baristas with 25 / 2 and gets 12. Explain why, give two ways to get 12.5, and explain why money is often stored as whole cents.