Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 134 ยท Standard Library

BigDecimal, Rational and Complex

Do exact math in Ruby - why 0.1 + 0.2 is off, BigDecimal for money, Rational fractions, Complex numbers, rounding modes, conversions and when to pick which type.

Ruby's everyday numbers are Integer and Float. Integers are exact and as large as memory allows (see Numbers). Floats are fast but approximate, because they store binary fractions: 0.1 + 0.2 is not exactly 0.3. For most science and graphics that is fine. For prices, tax and ledgers it is a bug waiting to happen.

Ruby ships three more numeric types for the cases where floats are the wrong tool. Rational is an exact fraction such as 1/3. BigDecimal is an exact decimal number with a chosen precision, ideal for money. Complex has a real and an imaginary part, for engineering and signal work. All three behave like numbers: they support + - * /, comparison, round, and mix with integers.

Why floats surprise you

Ruby The float problem

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.

Comparing floats with == is a trap. The two usual fixes are to compare with a tolerance, or to leave binary floating point altogether, which is what the rest of this lesson is about. Storing money as an integer number of cents is simple and valid, but you must do your own rounding when you apply a percentage. BigDecimal and Rational do that arithmetic for you.

Rational: exact fractions

A Rational is a numerator and a denominator, always reduced. Create one with the literal suffix r (3/4r), with Rational(a, b), or with Integer#quo/to_r.

Ruby Rational arithmetic

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.

0.1.to_r shows the true value stored in the float: a huge fraction that is almost one tenth. rationalize finds the simplest fraction within a tolerance, which is usually what you meant. Rationals are slower than floats, and denominators can grow large in long computations, but nothing is ever lost.

BigDecimal: exact decimal numbers

BigDecimal stores digits in base 10, so decimal fractions like 0.1 are exact. It comes from the bigdecimal library. In current Rubies it is a bundled gem, so add gem "bigdecimal" to a Gemfile in a Bundler project; in a plain script require "bigdecimal" works. The bigdecimal/util extension adds to_d to strings, numbers and rationals.

Ruby BigDecimal for money

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 rules that keep money code correct:

  1. Build from strings (BigDecimal("19.99")) or integers, never from a float literal. 19.99 is already approximate before BigDecimal sees it.
  2. Round explicitly at the points where your business rules say (per line item, or on the total). round(2) rounds to two decimals; the half: option picks :up, :down or :even ("banker's rounding").
  3. Format at the edge. to_s("F") prints plain digits; to_f is fine for display or charts, but never feed it back into calculations.
  4. Division of BigDecimals gives a result with limited precision (like 1/3 above). Use div(other, digits) to choose the number of digits.
flowchart TD
  Q["What are you calculating?"] --> A{"Exact decimal digits<br/>(money, tax, units)?"}
  A -->|yes| BD["BigDecimal<br/>or integer cents"]
  A -->|no| B{"Exact fractions<br/>(1/3, ratios)?"}
  B -->|yes| R["Rational"]
  B -->|no| C{"Real and imaginary parts?"}
  C -->|yes| CX["Complex"]
  C -->|no| F["Float (fast, approximate)<br/>or Integer"]

Choosing a numeric type: exactness and the shape of the number decide.

Complex numbers

A Complex number is a + bi where i is the square root of -1. Ruby has a literal suffix i (2+3i) and Complex(real, imaginary). Complex is in the core, so no require is needed. Math.sqrt(-4) raises Math::DomainError because Math works on real numbers only; with Complex you can raise to the power 0.5 and get an answer.

Ruby Complex arithmetic

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.

Complex numbers can have Integer, Float or Rational parts. abs is the length of the arrow from the origin, arg its angle. Complex numbers are not ordered: Complex(1, 2) < Complex(2, 3) raises NoMethodError, because there is no meaningful "bigger".

Mixing the types: coerce and conversions

Ruby promotes numbers when you mix them, following a simple "generality" order: Integer, then Rational, then Float, then Complex. Mixing BigDecimal with Float gives a BigDecimal for + but is easy to misuse, so convert deliberately.

Ruby What type comes out?

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 surprise is 1 / 2, which is 0 because both are integers. When you want an exact fraction, use quo (or write 1/2r). The sum of an Integer and a Rational is a Rational; adding a Float anywhere turns the answer into a Float, and from there on it is approximate again. Convert once at the boundary and keep the calculation in one type.

Which one should I use?

  • Money, tax, interest, anything decimal that must match a paper total: BigDecimal (or integer cents).
  • Ratios, fractions, repeating decimals, exact comparisons: Rational.
  • Physics, graphics, statistics and machine learning: Float, with tolerant comparisons ((a - b).abs < 1e-9).
  • Counting, indexes, huge exact numbers: Integer.
  • Roots of polynomials, signals, rotations: Complex.

When measuring performance, floats win by a wide margin; exact types cost time (see Benchmarking). In most business code the cost is irrelevant next to correctness.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is 0.1 + 0.2 == 0.3 false in Ruby?

    Binary floating point approximates most decimal fractions. The sum is very close to 0.3 but not equal, so compare with a tolerance or use an exact type.
  2. 2. How should you create a BigDecimal for the price 19.99?

    A string carries the exact decimal digits. A float literal is already approximate before BigDecimal ever sees it.
  3. 3. What does 1.quo(2) return?

    quo performs exact division and returns a Rational for integer operands, while 1 / 2 is integer division and gives 0.
  4. 4. Which statement about Complex numbers is true?

    Complex is built in and parts may be Integer, Float or Rational. There is no natural order for complex numbers, so < is not defined.

Summary

  • Floats are approximate; never compare them with == and avoid them for money.
  • Rational (3/4r) is an exact fraction; quo and rationalize produce rationals.
  • BigDecimal (from bigdecimal, with bigdecimal/util for to_d) stores exact decimal digits; build it from strings and round explicitly.
  • Complex (2+3i) has real and imaginary parts, with abs, arg, polar and conjugate.
  • Adding a Float to an exact type returns a Float; convert deliberately and keep calculations in one type.

Next: Heredocs and sprintf/format