Codectionary / Developer documentation / Ruby

BigDecimal Arithmetic

BigDecimal calculates with decimal values rather than binary Float approximations. Require bigdecimal and create values from strings when preserving decimal input matters. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

BigDecimal("0.1"); value.to_s("F")

Examples

BigDecimal Arithmetic

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

require "bigdecimal"
total = BigDecimal("0.10") + BigDecimal("0.20")
puts total.to_s("F")
puts total == BigDecimal("0.3")
  1. Expected output: 0.3 true
  2. The sum is the exact decimal 0.3. The F formatting option selects ordinary decimal notation instead of exponential notation.

Best practices

  • Do not first convert input through Float when exact decimal values are required.
  • Define a rounding policy and declare the bigdecimal gem when using Bundler.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading