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.5Integer 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.3That 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 # => 3The 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.
The problem
Tips total 25 dollars, shared by 2 baristas. You write
25 / 2.
Drills
Answer fast — trust the rule.
What is 9 / 4 in Ruby?
What is 9 / 4.0?
What is 17 % 5?
What does 0.1 + 0.2 == 0.3 return?
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 / 2is3, and floats are approximate, so handle money in whole cents or BigDecimal.
