Rational and BigDecimal

suggest change

Float is a binary floating-point number. It's fast, but it can't exactly represent most decimal fractions such as 0.1, so small errors creep into calculations:

p 0.1 + 0.2          # => 0.30000000000000004
p 0.1 + 0.2 == 0.3   # => false
p 1.15 * 100         # => 114.99999999999999
p (0.57 * 100).to_i  # => 56, not 57

total = 0.0
10.times { total += 0.1 }
p total              # => 0.9999999999999999

For money, measurements, exact fractions and anything where these errors matter, Ruby gives you two exact numeric types:

Both give the right answer here:

require "bigdecimal"

r = 0r
10.times { r += 1/10r }
p r # => (1/1)

d = BigDecimal("0")
10.times { d += BigDecimal("0.1") }
p d # => 0.1e1

There's a shorter introduction in Rational Numbers. This article goes further into both types and when to use each one.

Rational

Creating rationals

A rational is always stored in lowest terms, and the sign is kept on the numerator:

p Rational(3, 6)    # => (1/2)
p Rational(-3, 6)   # => (-1/2)
p Rational(3, -5)   # => (-3/5)
p Rational(3)       # => (3/1)

The r suffix creates a rational literal. 1/3r is the integer 1 divided by the rational 3r, so the result is a rational too:

p 3r         # => (3/1)
p 0.75r      # => (3/4)   decimal literal with r is exact
p 1/3r       # => (1/3)
p 1/3r + 1/6r # => (1/2)
p 1.5r.class # => Rational

You can also parse strings. A decimal string is converted exactly:

p Rational("2/3")   # => (2/3)
p Rational("0.1")   # => (1/10)
p Rational("1.5e2") # => (150/1)
p "3/4".to_r        # => (3/4)
p "abc".to_r        # => (0/1)   String#to_r never raises

Converting from Float

Be careful when you convert a Float. Rational(0.1) and 0.1.to_r give the exact value of the binary float, which is not 1/10:

p Rational(0.1) # => (3602879701896397/36028797018963968)
p 0.1.to_r      # => (3602879701896397/36028797018963968)

Use rationalize to get the simplest fraction that's close to the float. You can pass an optional tolerance:

p 0.1.rationalize            # => (1/10)
p 0.333.rationalize(0.01r)   # => (1/3)

The best option is not to go through Float at all: write 0.1r, or parse the string "0.1".

Arithmetic

Arithmetic between rationals and integers stays exact:

r = Rational(7, 3)

p r.numerator    # => 7
p r.denominator  # => 3
p r + 1          # => (10/3)
p r * 3          # => (7/1)
p r / 2          # => (7/6)
p r ** 2         # => (49/9)
p r ** -1        # => (3/7)
p 1/3r * 3 == 1  # => true

Integer division with / truncates, but Integer#quo returns an exact rational:

p 7 / 2       # => 3
p 7.quo(2)    # => (7/2)
p 7.fdiv(2)   # => 3.5

See Dividing two numbers for more about division.

Mixing a rational with a Float gives a Float, so the exactness is gone:

p Rational(7, 3) + 0.5          # => 2.8333333333333335
p Rational(4, 9) ** Rational(1, 2) # => 0.6666666666666666

A fractional power usually has no exact rational result, so it returns a Float too. Dividing by zero raises an error:

Rational(1, 0) # ZeroDivisionError: divided by 0

Comparisons work across all numeric types, and rationals that are equal hash the same, so they're safe to use as hash keys:

p Rational(1, 2) == 0.5                          # => true
p 3r == 3                                        # => true
p [Rational(1, 3), 0.3, Rational(2, 7)].max      # => (1/3)
p Rational(1, 3).hash == Rational(2, 6).hash     # => true
p Rational(-7, 2).abs                            # => (7/2)
p Rational(7, 2).divmod(1)                       # => [3, (1/2)]

Rounding and converting

r = Rational(7, 3)

p r.to_f      # => 2.3333333333333335
p r.to_i      # => 2   (truncates)
p r.round     # => 2
p r.floor     # => 2
p r.ceil      # => 3
p r.round(2)  # => (233/100)  still a Rational
p r.floor(1)  # => (23/10)

When you give a number of digits, round, floor, ceil and truncate return a Rational. Without it they return an Integer.

By default halves are rounded away from zero. Use half: :even for banker's rounding:

p Rational(5, 2).round               # => 3
p Rational(-5, 2).round              # => -3
p Rational(5, 2).round(half: :even)  # => 2
p Rational(5, 2).round(half: :down)  # => 2

to_s and inspect show the fraction. To show a decimal, round it and format it:

p Rational(1, 3).to_s       # => "1/3"
p Rational(1, 3).inspect    # => "(1/3)"
p "%.4f" % Rational(1, 3)   # => "0.3333"

See Rounding Numbers for rounding in general.

When Rational shines

Use Rational when the values really are fractions: ratios, probabilities, scaling, averages that must be exact, or any calculation where you round only once at the end.

def mean(xs) = xs.sum(0r) / xs.size

p mean([1, 2, 2])                # => (5/3)
p mean([1, 2, 2]).round(3).to_f  # => 1.667

# exact probability of 10 heads in a row
p Rational(1, 2) ** 10           # => (1/1024)

# harmonic number H(20), exactly and as a float
p (1..20).sum { Rational(1, _1) } # => (55835135/15519504)
p (1..20).sum { 1.0 / _1 }        # => 3.597739657143682

Scaling a recipe by 1.5 and printing mixed fractions:

recipe = { flour: 3/4r, sugar: 1/3r, butter: 1/2r }
scaled = recipe.transform_values { _1 * 3/2r }
p scaled # => {flour: (9/8), sugar: (1/2), butter: (3/4)}

scaled.each do |name, v|
  whole, frac = v.divmod(1)
  parts = []
  parts << whole unless whole.zero?
  parts << frac unless frac.zero?
  puts "#{name}: #{parts.join(' ')}"
end

Output:

flour: 1 1/8
sugar: 1/2
butter: 3/4

The downside: numerators and denominators can grow very large in long calculations (look at H(20) above). That makes the math slower, and with something like a loan schedule you'd still need to round to cents at every step anyway. That kind of work is what BigDecimal is for.

BigDecimal

BigDecimal is an arbitrary-precision decimal number. 0.1 is stored as exactly one tenth, and you choose how many digits to keep when a result can't be exact, as with 1/3.

Since Ruby 3.4 bigdecimal is a bundled gem, not a default gem. It still comes with Ruby, but when you use Bundler you have to list it in your Gemfile:

# Gemfile
gem "bigdecimal"
require "bigdecimal"
require "bigdecimal/util" # adds to_d to String, Integer, Float, Rational

p BigDecimal::VERSION # => "4.1.3"  (Ruby 4.0 ships with 4.0.1)

Creating BigDecimal values

The safest way to create one is from a string:

p BigDecimal("0.1")       # => 0.1e0
p BigDecimal("19.99")     # => 0.1999e2
p BigDecimal("  12.5  ")  # => 0.125e2
p BigDecimal(42)          # => 0.42e2
p BigDecimal("Infinity")  # => Infinity

inspect uses scientific notation: 0.1999e2 means 0.1999 × 10², which is 19.99.

BigDecimal() is strict and raises on bad input. String#to_d is lenient, like to_f:

BigDecimal("abc")    # ArgumentError: invalid value for BigDecimal(): "abc"
BigDecimal("12.5kg") # ArgumentError: invalid value for BigDecimal(): "12.5kg"

p "abc".to_d     # => 0.0
p "12.5kg".to_d  # => 0.125e2

So use BigDecimal(str) for input you need to validate, such as user input or config files.

You can also convert other numbers. A Rational needs to be told how many significant digits to keep:

p "19.99".to_d               # => 0.1999e2
p 3.to_d                     # => 0.3e1
p 0.1.to_d                   # => 0.1e0
p BigDecimal(Rational(1, 3), 10) # => 0.3333333333e0
p Rational(1, 3).to_d(5)     # => 0.33333e0
p BigDecimal(0.1, 5)         # => 0.1e0

Current versions of bigdecimal convert a Float using its shortest decimal representation, so 0.1.to_d gives 0.1. Older versions raised ArgumentError when you called BigDecimal(float) without a precision. Either way, a float may already be wrong before you convert it, so don't let floats into money code at all. Parse the strings directly.

Arithmetic and precision

Addition, subtraction and multiplication are exact:

a = BigDecimal("0.1")
b = BigDecimal("0.2")

p a + b                       # => 0.3e0
p a + b == BigDecimal("0.3")  # => true
p BigDecimal("1.15") * 100    # => 0.115e3
p (BigDecimal("0.57") * 100).to_i # => 57
p BigDecimal("1.05") ** 10    # => 0.162889462677744140625e1

Division often can't be exact, so / picks a precision for you (here about 32 digits). Use div(value, digits) to set the number of significant digits yourself:

p BigDecimal("10") / 3                      # => 0.33333333333333333333333333333333e1
p BigDecimal("1").div(BigDecimal("3"), 30)  # => 0.333333333333333333333333333333e0
p BigDecimal("2").sqrt(30)                  # => 0.141421356237309504880168872421e1
p BigDecimal("1.05").power(10, 8)           # => 0.16288946e1

div with only one argument does integer (floor) division and returns an Integer, like Integer#div:

p BigDecimal("7").div(2)  # => 3
p BigDecimal("7.5") % 2   # => 0.15e1

Mixing types: an Integer, Rational or Float combined with a BigDecimal gives a BigDecimal. A String doesn't get converted:

p BigDecimal("19.99") + 1             # => 0.2099e2
p (BigDecimal("19.99") + 1.5).class   # => BigDecimal
p Rational(1, 3) + BigDecimal("0.1")  # => 0.43333333333333333333333333333333e0
BigDecimal("1") + "2"                 # TypeError: String can't be coerced into BigDecimal

Summing a list works best with an explicit starting value, so the result is a BigDecimal even when the list is empty:

prices = %w[19.99 5.01 0.10]
p prices.sum(BigDecimal("0")) { _1.to_d } # => 0.251e2
p [].sum(BigDecimal("0"))                # => 0.0

Rounding

round(n) rounds to n digits after the decimal point. By default halves round up (away from zero), which is what most people expect from school:

p BigDecimal("2.675").round(2)  # => 0.268e1
p BigDecimal("2.665").round(2)  # => 0.267e1
p BigDecimal("-0.005").round(2) # => -0.1e-1

The second argument picks a rounding mode. You can pass a symbol, a BigDecimal::ROUND_* constant, or half: like Float#round:

d = BigDecimal("2.665")
p d.round(2, half: :even)                   # => 0.266e1  banker's rounding
p d.round(2, :banker)                       # => 0.266e1
p d.round(2, BigDecimal::ROUND_HALF_EVEN)   # => 0.266e1

p BigDecimal("2.679").round(2, :down)       # => 0.267e1   toward zero
p BigDecimal("2.671").round(2, :up)         # => 0.268e1   away from zero
p BigDecimal("-2.671").round(2, :floor)     # => -0.268e1
p BigDecimal("2.671").round(2, :ceiling)    # => 0.268e1
Mode Symbol(s) 2.665 → -2.665 →
ROUND_HALF_UP (default) :half_up, :default 2.67 -2.67
ROUND_HALF_EVEN :half_even, :banker 2.66 -2.66
ROUND_HALF_DOWN :half_down 2.66 -2.66
ROUND_UP :up 2.67 -2.67
ROUND_DOWN :down, :truncate 2.66 -2.66
ROUND_CEILING :ceiling, :ceil 2.67 -2.66
ROUND_FLOOR :floor 2.66 -2.67

truncate, floor and ceil also accept a number of digits. Called with no argument (or 0), round returns an Integer:

p BigDecimal("1.23456").truncate(2) # => 0.123e1
p BigDecimal("1.23456").floor(3)    # => 0.1234e1
p BigDecimal("1.23456").ceil(3)     # => 0.1235e1
p BigDecimal("2.5").round           # => 3
p BigDecimal("2.5").round.class     # => Integer

You can change the default rounding mode for the current thread. Wrap the change in save_rounding_mode so it doesn't affect other code:

result = BigDecimal.save_rounding_mode do
  BigDecimal.mode(BigDecimal::ROUND_MODE, :half_even)
  BigDecimal("2.665").round(2)
end
p result                         # => 0.266e1
p BigDecimal("2.665").round(2)   # => 0.267e1  default restored

Usually it's clearer to pass the mode to each round call instead.

Converting and formatting

to_s uses scientific notation by default. Pass "F" for plain notation, optionally with a number to group digits:

d = BigDecimal("123.4500")
p d.to_s                                  # => "0.12345e3"
p d.to_s("F")                             # => "123.45"
p BigDecimal("1234567.891").to_s("3F")    # => "1 234 567.891"
p BigDecimal("1e-20").to_s("F")           # => "0.00000000000000000001"
p BigDecimal("100").to_s("F")             # => "100.0"
puts BigDecimal("0.1") + BigDecimal("0.2") # prints 0.3e0

Trailing zeros are not kept: BigDecimal("4.10").to_s("F") is "4.1". format("%.2f", d) gives two decimals, but it converts to Float first, so it loses digits on very large values. This helper stays exact:

def money(d)
  int, frac = d.round(2).to_s("F").split(".")
  "#{int}.#{frac.ljust(2, '0')}"
end

big = "12345678901234567.895".to_d
p money("4.1".to_d)    # => "4.10"
p money(big)           # => "12345678901234567.90"
p format("%.2f", big)  # => "12345678901234568.00"  wrong digits via Float

Converting to other numeric types:

d = BigDecimal("19.99")
p d.to_f  # => 19.99
p d.to_i  # => 19
p d.to_r  # => (1999/100)  exact

Comparison and inspection

Equality compares the value, and trailing zeros don't matter:

p BigDecimal("1.50") == BigDecimal("1.5")            # => true
p BigDecimal("1.50").hash == BigDecimal("1.5").hash  # => true
p BigDecimal("3") > 2                                # => true
p [BigDecimal("2.5"), 3, 1.5, Rational(7, 2)].sort   # => [1.5, 0.25e1, 3, (7/2)]

A few useful inspection methods:

d = BigDecimal("123.456")
p d.precision            # => 6   significant digits
p d.scale                # => 3   digits after the decimal point
p d.exponent             # => 3   d = 0.123456 * 10**3
p d.sign                 # => 2   BigDecimal::SIGN_POSITIVE_FINITE
p BigDecimal("-3.7").frac  # => -0.7e0
p BigDecimal("-3.7").fix   # => -0.3e1

Infinity, NaN and exceptions

Unlike Float, BigDecimal doesn't overflow at around 1e308:

p 1e308 * 10                 # => Infinity
p BigDecimal("1e400") * 2    # => 0.2e401

By default, dividing a BigDecimal by zero with / returns Infinity or NaN instead of raising. You can turn on exceptions for the current thread:

p BigDecimal("1") / 0          # => Infinity
p BigDecimal("0") / 0          # => NaN
p BigDecimal("1").div(0)       # ZeroDivisionError (integer division always raises)

BigDecimal.mode(BigDecimal::EXCEPTION_ZERODIVIDE, true)
BigDecimal("1") / 0            # FloatDomainError: Divide by zero

Check for special values with nan?, infinite? (returns 1, -1 or nil) and finite?.

BigMath

bigdecimal/math provides constants and functions with any precision you ask for:

require "bigdecimal/math"

p BigMath.PI(20)                     # => 0.31415926535897932385e1
p BigMath.exp(BigDecimal("1"), 20)   # => 0.27182818284590452354e1
p BigMath.log(BigDecimal("2"), 20)   # => 0.69314718055994530942e0

A worked example: an invoice

require "bigdecimal"
require "bigdecimal/util"

Line = Struct.new(:name, :price, :qty)

lines = [
  Line.new("Keyboard", "49.99".to_d, 2),
  Line.new("Mouse",    "19.95".to_d, 3),
  Line.new("Cable",     "4.10".to_d, 5),
]
tax_rate = "0.0825".to_d

subtotal = lines.sum(BigDecimal("0")) { |l| l.price * l.qty }
tax      = (subtotal * tax_rate).round(2, half: :even)
total    = subtotal + tax

def money(d) = format("%.2f", d)

lines.each { |l| puts format("%-10s %3d x %8s", l.name, l.qty, money(l.price)) }
puts format("Subtotal: %10s", money(subtotal))
puts format("Tax:      %10s", money(tax))
puts format("Total:    %10s", money(total))

Output:

Keyboard     2 x    49.99
Mouse        3 x    19.95
Cable        5 x     4.10
Subtotal:     180.33
Tax:           14.88
Total:        195.21

Splitting an amount evenly is a classic problem: 100.00 / 3 doesn't divide into cents. Work in integer cents and give the leftover cents to the first shares:

def split(amount, parts)
  cents = (amount * 100).to_i
  base, extra = cents.divmod(parts)
  Array.new(parts) { |i| BigDecimal(base + (i < extra ? 1 : 0)) / 100 }
end

shares = split(BigDecimal("100.00"), 3)
p shares.map { format("%.2f", _1) } # => ["33.34", "33.33", "33.33"]
p shares.sum == 100                 # => true

Monthly compound interest, rounding to cents every month like a bank does:

balance = BigDecimal("10000")
monthly = BigDecimal("0.05") / 12
12.times { balance = (balance * (1 + monthly)).round(2, half: :even) }
puts format("%.2f", balance) # => 10511.64

Choosing a numeric type

Type Exact? Speed Good for
Integer yes fastest counts; money stored as integer cents
Float no fast science, graphics, statistics, anything that tolerates tiny errors
Rational yes, always slower; numbers can grow large fractions, ratios, exact intermediate results
BigDecimal exact for + - *, chosen precision for / slower money, decimal input from users or databases, fixed-point math

A rough benchmark of 200,000 additions of 0.1:

                 user     system      total        real
Float        0.004623   0.000000   0.004623 (  0.004624)
Rational     0.026313   0.000018   0.026331 (  0.026333)
BigDecimal   0.026608   0.000000   0.026608 (  0.026611)

Both exact types are several times slower than Float. That rarely matters for business logic, but it does matter in tight numeric loops.

Practical rules:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents