Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 134 ยท Getting Started

Numbers

Master Ruby numbers - integer division, modulo, big integers, float precision, rounding, Rational, Complex, Integer methods and the Math module, with examples.

Numbers look simple until they surprise you. Why does 7 / 2 give 3? Why does -7 % 3 give 2? Why is 0.1 + 0.2 not 0.3, and how large can an integer be? Ruby answers these questions in a consistent way, and it gives you better tools than most languages for the cases where plain floating point is not good enough: unlimited integers, exact fractions with Rational, and complex numbers.

This lesson covers the numeric classes, the arithmetic operators and their edge cases, rounding, a tour of the most useful Integer and Float methods, Rational and Complex, and the Math module. Along the way you will meet the two errors numeric code produces most often.

Integer arithmetic

Ruby The arithmetic operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The surprising lines are the last two. Ruby's integer division floors: it rounds toward negative infinity, so -7 / 2 is -4, not -3 as in C or Java. The % operator is consistent with that rule: a == (a / b) * b + a % b always holds, which gives -7 % 3 == 2. If you want the remainder with the sign of the dividend (the C behavior), use remainder; divmod returns both quotient and modulo in one call.

Ruby divmod, remainder and floor semantics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

divmod with multiple assignment is the neat way to split a total into units (hours and minutes, dollars and cents, pages and lines).

Integers have no size limit

In many languages integers overflow at 2^31 or 2^63. Ruby's Integer grows as needed (the class is the same; only the internal representation changes).

Ruby Big integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The factorial of 50 has 65 digits and is computed exactly. Very large numbers are slower than small ones, but for everyday programs you can forget about overflow. This makes Ruby pleasant for puzzles, cryptography exercises and exact counting. digits returns the decimal digits from the least significant end, which makes digit-sum problems one line long.

Writing number literals

Ruby Number literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Floats and their limits

A Float is a 64-bit binary floating-point number, the same format as double in C and Java and Number in JavaScript. It is fast and handles a huge range, but it cannot represent most decimal fractions exactly.

Ruby Why 0.1 + 0.2 is not 0.3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Never compare floats with == after arithmetic. Either round both sides, or test that the difference is tiny. Also notice that dividing a float by zero does not raise an error: you get Infinity, -Infinity or NaN ("not a number"). Dividing an integer by zero does raise:

Ruby Integer division by zero (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints Infinity. The second stops with main.rb:2:in 'Integer#/': divided by 0 (ZeroDivisionError). The modulo operator raises the same error: 10 % 0 fails with in 'Integer#%': divided by 0.

Do not use Float for money. Store cents as integers (1999 for 19.99), or use Rational or BigDecimal when exact decimal behavior matters.

Rounding

round, floor, ceil and truncate work on floats (and also on integers with a negative digits argument).

Ruby Rounding in all directions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby rounds halves away from zero by default, which is what people learn at school. The half: option selects other rules, such as banker's rounding (:even), used in finance and statistics to avoid bias. A negative digits argument rounds an integer to tens, hundreds or thousands.

Useful Integer methods

Integers carry a surprising number of helpers, all called with the dot syntax.

Ruby A toolbox of Integer methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

times, upto, downto and step are the Ruby way to repeat something a number of times, and they take a block. Iterators and Blocks Basics shows why Ruby prefers them to counting loops. The questions even?, zero? and positive? end with ? because they return true or false. Integer.sqrt gives an exact integer answer for very large numbers, where Math.sqrt would lose precision.

Rational and Complex

For exact fractions, Rational stores a numerator and a denominator, so no precision is lost:

Ruby Exact fractions with Rational

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The suffix r creates a Rational literal, and 0.1r + 0.2r == 0.3r is true because decimal fractions are stored exactly. That makes Rational a good choice for money-like calculations of modest size.

Complex handles numbers with an imaginary part, useful in signal processing and mathematics:

Ruby Complex numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The Math module

Math holds functions and constants. Call them with the module name, such as Math.sqrt(16).

Ruby Math functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Math.log is the natural logarithm; give a base as a second argument for others. Angles are in radians. Square roots of negative numbers are an error, because Math.sqrt does not return complex numbers:

Ruby Math domain error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The result is main.rb:1:in 'Math.sqrt': Numerical argument is out of domain - sqrt (Math::DomainError). Check the input first, or use Complex when imaginary results are acceptable.

Formatting numbers for display

Raw numbers are rarely what you show to users. format (alias sprintf) and the % operator control width, padding and decimals; a little more is needed for thousands separators.

Ruby Formatting numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The method with_commas reverses the digits, takes groups of up to three, joins them with commas and reverses again. It does not handle negative numbers or decimals, a good small exercise. The format directives are covered fully in Reading Input and Formatting Output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -7 / 2 return in Ruby?

    Ruby's integer division rounds toward negative infinity (floor division), so -7 / 2 is -4. Use remainder or truncate if you need C-style behavior.
  2. 2. What does 10 / 0 do, compared with 10.0 / 0?

    Integer division by zero is an error. Floating-point division follows the IEEE standard and yields Infinity, -Infinity or NaN.
  3. 3. Which approach is best for comparing two computed floats?

    Binary floats cannot store most decimal fractions exactly, so 0.1 + 0.2 == 0.3 is false. Compare with a tolerance.
  4. 4. What is 2.5.round?

    By default halves round away from zero, giving 3. Use round(half: :even) for banker's rounding, which gives 2.
  5. 5. How large can an Integer be in Ruby?

    Integer has no fixed limit. Bignum was merged into Integer long ago and no longer exists.

Summary

  • Integer / Integer floors toward negative infinity; % follows the divisor's sign; divmod returns both, remainder keeps the dividend's sign.
  • Integers have no size limit; digits, gcd, lcm, pow and Integer.sqrt are handy built-ins.
  • Float is binary and approximate: compare with a tolerance and never store money in floats.
  • Float division by zero gives Infinity or NaN; integer division by zero raises ZeroDivisionError.
  • round rounds halves away from zero by default (half: :even for banker's rounding); floor, ceil and truncate round in other directions, and negative digits round integers.
  • Rational (1/3r) is exact; Complex supports imaginary parts; Math provides roots, logs and trigonometry, and raises Math::DomainError outside its domain.
  • format and % control how numbers are displayed.

Next: Strings