cockroachdb / apd

Arbitrary-precision decimals for Go
https://pkg.go.dev/github.com/cockroachdb/apd/v2
Apache License 2.0
639 stars 34 forks source link

apd

apd is an arbitrary-precision decimal package for Go.

apd implements much of the decimal specification from the General Decimal Arithmetic description. This is the same specification implemented by python’s decimal module and GCC’s decimal extension.

Features

apd has three main types.

The first is BigInt which is a wrapper around big.Int that exposes an identical API while reducing memory allocations. BigInt does so by using an inline array to back the big.Int's variable-length value when the integer's absolute value is sufficiently small. BigInt also contains fast-paths that allow it to perform basic arithmetic directly on this inline array, only falling back to big.Int when the arithmetic gets complex or takes place on large values.

The second is Decimal which holds the values of decimals. It is simple and uses a BigInt with an exponent to describe values. Most operations on Decimals can’t produce errors as they work directly on the underlying big.Int. Notably, however, there are no arithmetic operations on Decimals.

The third main type is Context, which is where all arithmetic operations are defined. A Context describes the precision, range, and some other restrictions during operations. These operations can all produce failures, and so return errors.

Context operations, in addition to errors, return a Condition, which is a bitfield of flags that occurred during an operation. These include overflow, underflow, inexact, rounded, and others. The Traps field of a Context can be set which will produce an error if the corresponding flag occurs. An example of this is given below.

See the examples for some operations that were previously difficult to perform in Go.

Documentation

https://pkg.go.dev/github.com/cockroachdb/apd/v3?tab=doc