bigdecimal

How does bigdecimal compare to float?

BigDecimal and Float serve different purposes in Ruby, each with distinct tradeoffs:

Precision

BigDecimal provides arbitrary precision decimal arithmetic. It stores numbers as exact decimal values, making it ideal for financial calculations where precision is critical. For example:

require 'bigdecimal'
BigDecimal("0.1") + BigDecimal("0.2") == BigDecimal("0.3")  # true

Float uses binary floating-point arithmetic (IEEE 754 standard). This can lead to rounding errors with decimal numbers:

0.1 + 0.2 == 0.3  # false (actually 0.30000000000000004)

Performance

Float is significantly faster because it uses hardware-level floating-point operations. Operations are computed directly by the CPU.

BigDecimal is slower since it performs calculations in software and must maintain exact decimal precision. The performance difference can be 10-100x depending on the operation.

Memory Usage

Float uses a fixed 8 bytes (64 bits) regardless of the value.

BigDecimal memory usage grows with the precision required. Simple values may use ~40 bytes, but this increases with more significant digits.

Use Cases

Use BigDecimal when:

  • Handling money and financial calculations
  • Exact decimal representation is required
  • You need arbitrary precision
  • Regulatory compliance requires exact decimal math

Use Float when:

  • Performance is critical
  • Approximate values are acceptable
  • Working with scientific/engineering calculations
  • Interfacing with systems that use floating-point

Example

# Financial calculation - use BigDecimal
require 'bigdecimal'
price = BigDecimal("19.99")
tax_rate = BigDecimal("0.08")
total = price * (1 + tax_rate)  # 21.5892 exactly

# Scientific calculation - Float is fine
distance = 149.6e6  # kilometers to sun
speed = 299792.458  # km/s
time = distance / speed  # approximate time for light to reach Earth