Current section
Files
Jump to
Current section
Files
README.md
# DecimalArbitrary precision decimal arithmetic.## ConceptDecimal represents values internally using three integers: a sign, a coefficient, and an exponent.In this way, numbers of any size and with any number of decimal places can be represented exactly.```elixirDecimal.new(_sign = 1, _coefficient = 42, _exponent = 0) #=> Decimal.new("42")Decimal.new(-1, 42, 0) #=> Decimal.new("-42")Decimal.new(1, 42, -1) #=> Decimal.new("4.2")Decimal.new(1, 42, -20) #=> Decimal.new("4.2E-19")Decimal.new(1, 42, 20) #=> Decimal.new("4.2E+21")Decimal.new(1, 123456789987654321, -9) #=> Decimal.new("123456789.987654321")```For calculations, the amount of desired precision - that is, the number ofdecimal digits in the coefficient - can be specified.## Handling untrusted inputDecimal can represent compact values with very large exponents, such as`1e1000000`. These values are valid decimals, but some operations can requirememory or CPU proportional to the expanded size of the number. This matters whendecimals are parsed from user input, JSON payloads, form fields, databasefields, or other external data.Use bounded parsing for untrusted input:```elixirDecimal.parse(input, max_digits: 100, max_exponent: 1000)Decimal.cast(input, max_digits: 100, max_exponent: 1000)```Use bounded output when rendering decimals in formats that may expand theexponent:```elixirDecimal.to_string(decimal, :normal, max_digits: 1000)Decimal.to_string(decimal, :xsd, max_digits: 1000)```The default scientific string format is compact for large positive exponents,but `:normal` and `:xsd` output can materialize many zeroes. APIs that convertto an integer or otherwise need the expanded value may also be expensive forlarge exponents. `Decimal.Context` supports finite `emax` and `emin` values tolimit operation results, but context limits do not validate already-createddecimals and should not replace parse/cast limits for untrusted input.## UsageAdd Decimal as a dependency in your `mix.exs` file:```elixirdef deps do [{:decimal, "~> 2.0"}]end```Next, run `mix deps.get` in your shell to fetch and compile `Decimal`. Start aninteractive Elixir shell with `iex -S mix`:```elixiriex> alias Decimal, as: Diex> D.add(6, 7)Decimal.new("13")iex> D.div(1, 3)Decimal.new("0.3333333333333333333333333333")iex> D.new("0.33")Decimal.new("0.33")```## Examples### Using the contextThe context specifies the maximum precision of the result of calculations andthe rounding algorithm if the result has a higher precision than the specifiedmaximum. It also holds the list of trap enablers and the current setflags.The context is stored in the process dictionary. You don't have to pass thecontext around explicitly and the flags will be updated automatically.The context is accessed with `Decimal.Context.get/0` and set with`Decimal.Context.set/1`. It can be set temporarily with`Decimal.Context.with/2`.```elixiriex> D.Context.get()%Decimal.Context{ precision: 9, rounding: :half_up, emax: :infinity, emin: :infinity, flags: [:rounded, :inexact], traps: [:invalid_operation, :division_by_zero]}iex> D.Context.with(%D.Context{precision: 2}, fn -> IO.inspect D.Context.get() end)%Decimal.Context{ precision: 2, rounding: :half_up, emax: :infinity, emin: :infinity, flags: [], traps: [:invalid_operation, :division_by_zero]}%Decimal.Context{ precision: 2, rounding: :half_up, emax: :infinity, emin: :infinity, flags: [], traps: [:invalid_operation, :division_by_zero]}iex> D.Context.set(%D.Context{D.Context.get() | traps: []}):okiex> D.Context.get()%Decimal.Context{ precision: 9, rounding: :half_up, emax: :infinity, emin: :infinity, flags: [:rounded, :inexact], traps: []}```### Precision and roundingUse `:precision` option to limit the amount of decimal digits in thecoefficient of any calculation result:```elixiriex> D.Context.set(%D.Context{D.Context.get() | precision: 9}):okiex> D.div(100, 3)Decimal.new("33.3333333")iex> D.Context.set(%D.Context{D.Context.get() | precision: 2}):okiex> D.div(100, 3)Decimal.new("33")```The `:rounding` option specifies the algorithm and precision of the roundingoperation:```elixiriex> D.Context.set(%D.Context{D.Context.get() | rounding: :half_up}):okiex> D.div(31, 2)Decimal.new("16")iex> D.Context.set(%D.Context{D.Context.get() | rounding: :floor}):okiex> D.div(31, 2)Decimal.new("15")```### ComparisonsUsing comparison operators (`<`, `=`, `>`) with two or more decimal digits maynot produce accurate result. Instead, use comparison functions.```elixiriex> D.compare(-1, 0):ltiex> D.compare(0, -1):gtiex> D.compare(0, 0):eqiex> D.equal?(-1, 0)falseiex> D.equal?(0, "0.0")true```### Flags and trap enablersWhen an exceptional condition is signalled, its flag is set in the currentcontext. `Decimal.Error` will be raised if the trap enabler is set.```elixiriex> D.Context.set(%D.Context{D.Context.get() | rounding: :floor, precision: 2}):okiex> D.Context.get().traps[:invalid_operation, :division_by_zero]iex> D.Context.get().flags[]iex> D.div(31, 2)Decimal.new("15")iex> D.Context.get().flags[:inexact, :rounded]````:inexact` and `:rounded` flag were signalled above because the result of theoperation was inexact given the context's precision and had to be rounded tofit the precision. `Decimal.Error` was not raised because the signals' trapenablers weren't set.```elixiriex> D.Context.set(%D.Context{D.Context.get() | traps: D.Context.get().traps ++ [:inexact]}):okiex> D.div(31, 2)** (Decimal.Error)```The default trap enablers, such as `:division_by_zero`, can be unset:```elixiriex> D.Context.get().traps[:invalid_operation, :division_by_zero]iex> D.div(42, 0)** (Decimal.Error)iex> D.Context.set(%D.Context{D.Context.get() | traps: [], flags: []}):okiex> D.div(42, 0)Decimal.new("Infinity")iex> D.Context.get().flags[:division_by_zero]```### Mitigating rounding errorsTODO## License Copyright 2013 Eric Meadows-Jönsson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.