:decimal (FakeDecimal v0.1.1)

Copy Markdown View Source

This library provides a :decimal module that has the same functions (API, interface) as the good^H^H^H^Hbad old erlang_decimal library, but it is just an interface to the Elixir Decimal library.

The old erlang_decimal used 2-tuples with integers in it to represent numbers, while the Elixir decimal uses structs. By using this library, the module :decimal serves as the old API, and the module Decimal as the new one. Unfortunately, the application names clash in the package decimal and erlang_decimal, so you cannot use them at once, but fake_decimal plays nicely with the Elixir decimal.

If there's a legacy application that calls into :decimal, but you also need the Elixir decimal library in your app, you may be able to provide the old API for the legacy app by using fake_decimal.

The functions where rounding semantics matter (round/3, divide/3, sqrt/2, cmp/3, fast_cmp/2, to_binary/1,2) reproduce the original erlang_decimal algorithms exactly: precision counts fractional digits (decimal places, not significant digits), and the round_half_up / round_half_down modes decide based on the first discarded digit only, just like the original.

Deviations from erlang_decimal

  • add/2, sub/2 and mult/2 results are normalized: add({1, 0}, {9, 0}) returns {1, 1} where the original returns {10, 0}. The two tuples are numerically equal (cmp/3 returns 0 and reduce/1 maps both to the same tuple), but code that pattern-matches exact tuples may see a different — equivalent — representation.

  • Wherever the original accepts only {coef, exp} tuples, this module also accepts Elixir Decimal structs, integers, floats, strings and charlists.

Summary

Functions

abs(a)

add(a, b)

cmp(a, b, opts)

divide(a, b, opts)

fast_cmp(a, b)

is_zero(a)

minus(a)

mult(a, b)

reduce(a)

round(mode, num, precision \\ 0)

sqrt(a, opts)

sub(a, b)

to_binary(a)

to_binary(a, opts)

to_decimal(value)

to_decimal(value, arg2)

to_decimal(base, exp, opts)