Overview
simple_decimal is a clean wrapper over Gobo's MA_DECIMAL library that provides arbitrary-precision decimal arithmetic for Eiffel. Perfect for financial calculations where binary floating-point errors are unacceptable.
The Problem with Floating-Point
Binary floating-point (REAL, DOUBLE) cannot represent many decimal fractions exactly:
-- DOUBLE fails silently!
io.put_double (0.1 + 0.2) -- Outputs: 0.30000000000000004 WRONG!
This causes real-world problems: financial calculations that don't balance, prices that display incorrectly, tax calculations off by a penny, and cumulative errors in accounting systems.
The Solution
local
a, b, total: SIMPLE_DECIMAL
do
create a.make ("0.1")
create b.make ("0.2")
total := a + b
print (total.out) -- Outputs: 0.3 CORRECT!
end
Quick Start
Installation
- Set the environment variable:
export SIMPLE_EIFFEL=/d/prod - Add to your ECF file:
<library name="simple_decimal" location="$SIMPLE_EIFFEL/simple_decimal/simple_decimal.ecf"/>
Basic Usage
class
INVOICE_CALCULATOR
feature -- Calculation
calculate_total (subtotal_str, tax_rate_str: STRING): STRING
-- Calculate total with tax, returning formatted currency
local
subtotal, tax_rate, tax, total: SIMPLE_DECIMAL
do
create subtotal.make (subtotal_str)
create tax_rate.make (tax_rate_str)
-- Calculate tax: subtotal * (rate / 100)
tax := (subtotal * tax_rate.from_percentage).round_cents
total := subtotal + tax
Result := total.to_currency_string
end
end
Result: calculate_total ("47.99", "8.25") returns "$51.95"
Key Features
Arbitrary Precision
No floating-point representation errors. 0.1 + 0.2 = 0.3 exactly.
Financial Operations
Currency formatting, percentages, tax calculations, bill splitting with penny-perfect accuracy.
Multiple Rounding Modes
Banker's rounding (half-even), round up, round down, ceiling, floor, truncate.
Immutable Operations
All arithmetic returns new values. Thread-safe, predictable, no side effects.
Smart Parsing
Handles "$1,234.56", "1234.56", "-$99.99" automatically.
Design by Contract
Full preconditions, postconditions, and class invariants throughout.
Documentation
- User Guide - Complete tutorial with examples
- API Reference - Full feature documentation
- Architecture - Internal design and rationale
- Cookbook - Real-world recipes and patterns
Standards Compliance
simple_decimal is built on Gobo's MA_DECIMAL which implements:
- General Decimal Arithmetic Specification - IBM's decimal arithmetic standard
- IEEE 754-2008 - Standard for floating-point arithmetic (decimal64/decimal128)
This means your calculations follow the same rules used by financial institutions worldwide.