Integers and Floats
Integer arithmetic stays whole and division drops the remainder, while any float in a calculation makes the result a float, which is approximate.
Inspect integer division and floating-point approximations before using the result.
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 # => 3