decimal: github.com/ericlagergren/decimal Index | Examples | Files | Directories

package decimal

import "github.com/ericlagergren/decimal"

Package decimal provides a high-performance, arbitrary precision, floating-point decimal library.

Overview

This package provides floating-point decimal numbers, useful for financial programming or calculations where a larger, more accurate representation of a number is required.

In addition to basic arithmetic operations (addition, subtraction, multiplication, and division) this package offers various mathematical functions, including the exponential function, various logarithms, and the ability to compute continued fractions.

While lean, this package is full of features. It implements interfaces like “fmt.Formatter” and intuitively utilizes verbs and flags as described in the “fmt” package. (Also included: “fmt.Scanner”, “fmt.Stringer”, “encoding.TextUnmarshaler”, and “encoding.TextMarshaler”.)

It allows users to specific explicit contexts for arithmetic operations, but doesn't require it. It provides access to NaN payloads and is more lenient when parsing a decimal from a string than the GDA specification requires.

API interfaces have been changed slightly to work more seamlessly with existing Go programs. For example, many “Quantize” implementations require a decimal as both the receiver and argument which isn't very user friendly. Instead, this library accepts a simple “int” which can be derived from an existing decimal if required.

It contains two modes of operation designed to make transitioning to various GDA "quirks" (like always rounding lossless operations) easier.

GDA: strictly adhere to the GDA specification (default)
Go: utilize Go idioms, more flexibility

Goals

There are three primary goals of this library:

1. Correctness

By adhering to the General Decimal Arithmetic specification, this package has a well-defined structure for its arithmetic operations.

2. Performance

Decimal libraries are inherently slow; this library works diligently to minimize memory allocations and utilize efficient algorithms. Performance regularly benchmarks as fast or faster than many other popular decimal libraries.

3. Ease of use

Libraries should be intuitive and work out of the box without having to configure too many settings; however, precise settings should still be available.

Usage

The following type is supported:

Big decimal numbers

The zero value for a Big corresponds with 0, meaning all the following are valid:

var x Big
y := new(Big)
z := &Big{}

Method naming is the same as math/big's, meaning:

func (z *T) SetV(v V) *T          // z = v
func (z *T) Unary(x *T) *T        // z = unary x
func (z *T) Binary(x, y *T) *T    // z = x binary y
func (x *T) Pred() P              // p = pred(x)

In general, its conventions mirror math/big's. It is suggested to read the math/big package comments to gain an understanding of this package's conventions.

Arguments to Binary and Unary methods are allowed to alias, so the following is valid:

x := New(1, 0)
x.Add(x, x) // x == 2

y := New(1, 0)
y.FMA(y, x, y) // y == 3

Unless otherwise specified, the only argument that will be modified is the result (“z”). This means the following is valid and race-free:

x := New(1, 0)
var g1, g2 Big

go func() { g1.Add(x, x) }()
go func() { g2.Add(x, x) }()

But this is not:

x := New(1, 0)
var g Big

go func() { g.Add(x, x) }() // BAD! RACE CONDITION!
go func() { g.Add(x, x) }() // BAD! RACE CONDITION!

Index

Examples

Package Files

big.go big_ctx.go context.go doc.go format.go format_string.go operatingmode_string.go roundingmode_string.go scan.go util.go zdebug0.go

Constants

const (
    MaxScale           = c.MaxScale       // largest allowed scale.
    MinScale           = -MaxScale        // smallest allowed scale.
    MaxPrecision       = MaxScale         // largest allowed Context precision.
    MinPrecision       = 1                // smallest allowed Context precision.
    UnlimitedPrecision = MaxPrecision + 1 // no precision, but may error.
    DefaultPrecision   = 16               // default precision for literals.
)

Precision and scale limits.

Variables

var (
    // Context32 is the IEEE 754R Decimal32 format.
    Context32 = Context{
        Precision:     7,
        RoundingMode:  ToNearestEven,
        OperatingMode: GDA,
        Traps:         ^(Inexact | Rounded | Subnormal),
        MaxScale:      96,
        MinScale:      -95,
    }

    // Context64 is the IEEE 754R Decimal64 format.
    Context64 = Context{
        Precision:     16,
        RoundingMode:  ToNearestEven,
        OperatingMode: GDA,
        Traps:         ^(Inexact | Rounded | Subnormal),
        MaxScale:      384,
        MinScale:      -383,
    }

    // Context128 is the IEEE 754R Decimal128 format.
    Context128 = Context{
        Precision:     34,
        RoundingMode:  ToNearestEven,
        OperatingMode: GDA,
        Traps:         ^(Inexact | Rounded | Subnormal),
        MaxScale:      6144,
        MinScale:      -6143,
    }

    // ContextUnlimited provides unlimited precision decimals.
    ContextUnlimited = Context{
        Precision:     UnlimitedPrecision,
        RoundingMode:  ToNearestEven,
        OperatingMode: GDA,
        Traps:         ^(Inexact | Rounded | Subnormal),
        MaxScale:      MaxScale,
        MinScale:      MinScale,
    }
)

The following Contexts are based on IEEE 754R. Each Context's RoundingMode is ToNearestEven, OperatingMode is GDA, and traps are set to every exception other than Inexact, Rounded, and Subnormal.

var Regexp = regexp.MustCompile(`(?i)(([+-]?(\d+\.\d*|\.?\d+)([eE][+-]?\d+)?)|(inf(infinity)?))|([+-]?([sq]?nan\d*))`)

Regexp matches any valid string representing a decimal that can be passed to SetString.

func Raw Uses

func Raw(x *Big) (*uint64, *big.Int)

Raw directly returns x's raw compact and unscaled values. Caveat emptor: Neither are guaranteed to be valid. Raw is intended to support missing functionality outside this package and generally should be avoided. Additionally, Raw is the only part of this package's API which is not guaranteed to remain stable. This means the function could change or disappear at any time, even across minor version numbers.

type Big Uses

type Big struct {
    // Context is the decimal's unique contextual object.
    Context Context
    // contains filtered or unexported fields
}

Big is a floating-point, arbitrary-precision decimal.

It is represented as a number and a scale. If the scale is >= 0, it indicates the number of decimal digits after the radix. Otherwise, the number is multiplied by 10 to the power of the negation of the scale. More formally,

Big = number × 10**-scale

with MinScale <= scale <= MaxScale. A Big may also be ±0, ±Infinity, or ±NaN (either quiet or signaling). Non-NaN Big values are ordered, defined as the result of x.Cmp(y).

Additionally, each Big value has a contextual object which governs arithmetic operations.

Code:

const input = "15 7 1 1 + - / 3 * 2 1 1 + + - 5 * 3 / ="
var stack []*Big
Loop:
for _, tok := range strings.Split(input, " ") {
    last := len(stack) - 1
    switch tok {
    case "+":
        x := stack[last-1]
        x.Add(x, stack[last])
        stack = stack[:last]
    case "-":
        x := stack[last-1]
        x.Sub(x, stack[last])
        stack = stack[:last]
    case "/":
        x := stack[last-1]
        x.Quo(x, stack[last])
        stack = stack[:last]
    case "*":
        x := stack[last-1]
        x.Mul(x, stack[last])
        stack = stack[:last]
    case "=":
        break Loop
    default:
        x := WithContext(Context128)
        if _, ok := x.SetString(tok); !ok {
            fmt.Fprintf(os.Stderr, "invalid decimal: %v\n", x.Context.Err())
            os.Exit(1)
        }
        stack = append(stack, x)
    }
}
fmt.Printf("%+6.4g\n", stack[0])

Output:

+8.333

func New Uses

func New(value int64, scale int) *Big

New creates a new Big decimal with the given value and scale. For example:

New(1234, 3) // 1.234
New(42, 0)   // 42
New(4321, 5) // 0.04321
New(-1, 0)   // -1
New(3, -10)  // 30 000 000 000

func WithContext Uses

func WithContext(c Context) *Big

WithContext is shorthand to create a Big decimal from a Context.

func WithPrecision Uses

func WithPrecision(p int) *Big

WithPrecision is shorthand to create a Big decimal with a given precision.

func (*Big) Abs Uses

func (z *Big) Abs(x *Big) *Big

Abs sets z to the absolute value of x and returns z.

func (*Big) Add Uses

func (z *Big) Add(x, y *Big) *Big

Add sets z to x + y and returns z.

func (*Big) CheckNaNs Uses

func (z *Big) CheckNaNs(x, y *Big) bool

CheckNaNs checks if either x or y is NaN. If so, it follows the rules of NaN handling set forth in the GDA specification. The second argument, y, may be nil. It returns true if either condition is a NaN.

func (*Big) Class Uses

func (x *Big) Class() string

Class returns the “class” of x, which is one of the following:

sNaN
NaN
-Infinity
-Normal
-Subnormal
-Zero
+Zero
+Subnormal
+Normal
+Infinity

func (*Big) Cmp Uses

func (x *Big) Cmp(y *Big) int

Cmp compares x and y and returns:

-1 if x <  y
 0 if x == y
+1 if x >  y

It does not modify x or y. The result is undefined if either x or y are NaN. For an abstract comparison with NaN values, see misc.CmpTotal.

func (*Big) CmpAbs Uses

func (x *Big) CmpAbs(y *Big) int

CmpAbs compares |x| and |y| and returns:

-1 if |x| <  |y|
 0 if |x| == |y|
+1 if |x| >  |y|

It does not modify x or y. The result is undefined if either x or y are NaN. For an abstract comparison with NaN values, see misc.CmpTotalAbs.

func (*Big) Copy Uses

func (z *Big) Copy(x *Big) *Big

Copy sets z to a copy of x and returns z.

func (*Big) CopySign Uses

func (z *Big) CopySign(x, y *Big) *Big

CopySign sets z to x with the sign of y and returns z. It accepts NaN values.

func (*Big) FMA Uses

func (z *Big) FMA(x, y, u *Big) *Big

FMA sets z to (x * y) + u without any intermediate rounding.

func (*Big) Float Uses

func (x *Big) Float(z *big.Float) *big.Float

Float sets z to x and returns z. z is allowed to be nil. The result is undefined if z is a NaN value.

func (*Big) Float64 Uses

func (x *Big) Float64() (f float64, ok bool)

Float64 returns x as a float64 and a bool indicating whether x can fit into a float64 without truncation, overflow, or underflow. Special values are considered exact; however, special values that occur because the magnitude of x is too large to be represented as a float64 are not.

func (*Big) Format Uses

func (x *Big) Format(s fmt.State, c rune)

Format implements the fmt.Formatter interface. The following verbs are supported:

%s: -dddd.dd or -d.dddd±edd, depending on x
%d: same as %s
%v: same as %s
%e: -d.dddd±edd
%E: -d.dddd±Edd
%f: -dddd.dd
%g: same as %f

While width is honored in the same manner as the fmt package (the minimum width of the formatted number), precision is the number of significant digits in the decimal number. Given %f, however, precision is the number of digits following the radix.

Format honors all flags (such as '+' and ' ') in the same manner as the fmt package, except for '#'. Unless used in conjunction with %v, %q, or %p, the '#' flag will be ignored; decimals have no defined hexadeximal or octal representation.

%+v, %#v, %T, %#p, and %p all honor the formats specified in the fmt package's documentation.

Code:

print := func(format, xs string) {
    x, _ := new(Big).SetString(xs)
    fmt.Printf(format+"\n", x)
}

print("%s", "12.34")
print("%.3g", "12.34")
print("%.1f", "12.34")
print("`%6.4g`", "500.44")
print("'%-10.f'", "-404.040")

Output:

12.34
12.3
12.3
` 500.4`
'-404      '

func (*Big) Int Uses

func (x *Big) Int(z *big.Int) *big.Int

Int sets z to x, truncating the fractional portion (if any) and returns z. z is allowed to be nil. If x is an infinity or a NaN value the result is undefined.

func (*Big) Int64 Uses

func (x *Big) Int64() (int64, bool)

Int64 returns x as an int64, truncating towards zero. The returned boolean indicates whether the conversion to an int64 was successful.

func (*Big) IsFinite Uses

func (x *Big) IsFinite() bool

IsFinite returns true if x is finite.

func (*Big) IsInf Uses

func (x *Big) IsInf(sign int) bool

IsInf returns true if x is an infinity according to sign. If sign > 0, IsInf reports whether x is positive infinity. If sign < 0, IsInf reports whether x is negative infinity. If sign == 0, IsInf reports whether x is either infinity.

func (*Big) IsInt Uses

func (x *Big) IsInt() bool

IsInt reports whether x is an integer. Infinity and NaN values are not integers.

func (*Big) IsNaN Uses

func (x *Big) IsNaN(quiet int) bool

IsNaN returns true if x is NaN. If sign > 0, IsNaN reports whether x is quiet NaN. If sign < 0, IsNaN reports whether x is signaling NaN. If sign == 0, IsNaN reports whether x is either NaN.

func (*Big) IsNormal Uses

func (x *Big) IsNormal() bool

IsNormal returns true if x is normal.

func (*Big) IsSubnormal Uses

func (x *Big) IsSubnormal() bool

IsSubnormal returns true if x is subnormal.

func (*Big) MarshalText Uses

func (x *Big) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Big) Mul Uses

func (z *Big) Mul(x, y *Big) *Big

Mul sets z to x * y and returns z.

func (*Big) Neg Uses

func (z *Big) Neg(x *Big) *Big

Neg sets z to -x and returns z. If x is positive infinity, z will be set to negative infinity and visa versa. If x == 0, z will be set to zero as well. NaN will result in an error.

func (*Big) Payload Uses

func (x *Big) Payload() Payload

Payload returns the payload of x, provided x is a NaN value. If x is not a NaN value, the result is undefined.

func (*Big) Precision Uses

func (x *Big) Precision() int

Precision returns the precision of x. That is, it returns the number of digits in the unscaled form of x. x == 0 has a precision of 1. The result is undefined if x is not finite.

Code:

a := New(12, 0)
b := New(42, -2)
c := New(12345, 3)
d := New(3, 5)

fmt.Printf(`
%s has a precision of %d
%s has a precision of %d
%s has a precision of %d
%s has a precision of %d
`, a, a.Precision(), b, b.Precision(), c, c.Precision(), d, d.Precision())

Output:

12 has a precision of 2
4.2E+3 has a precision of 2
12.345 has a precision of 5
0.00003 has a precision of 1

func (*Big) Quantize Uses

func (z *Big) Quantize(n int) *Big

Quantize sets z to the number equal in value and sign to z with the scale, n.

Code:

a, _ := WithContext(Context32).SetString("2.17")
b, _ := WithContext(Context64).SetString("217")
c, _ := WithContext(Context128).SetString("-0.1")
d, _ := WithContext(Context{OperatingMode: GDA}).SetString("-0")

fmt.Printf("A: %s\n", a.Quantize(3)) // 3 digits after radix
fmt.Printf("B: %s\n", b.Quantize(-2))
fmt.Printf("C: %s\n", c.Quantize(1))
fmt.Printf("D: %s\n", d.Quantize(-5))

Output:

A: 2.170
B: 2E+2
C: -0.1
D: -0E+5

func (*Big) Quo Uses

func (z *Big) Quo(x, y *Big) *Big

Quo sets z to x / y and returns z.

func (*Big) QuoInt Uses

func (z *Big) QuoInt(x, y *Big) *Big

QuoInt sets z to x / y with the remainder truncated. See QuoRem for more details.

func (*Big) QuoRem Uses

func (z *Big) QuoRem(x, y, r *Big) (*Big, *Big)

QuoRem sets z to the quotient x / y and r to the remainder x % y, such that x = z * y + r, and returns the pair (z, r).

func (*Big) Rat Uses

func (x *Big) Rat(z *big.Rat) *big.Rat

Rat sets z to x returns z. z is allowed to be nil. The result is undefined if x is an infinity or NaN value.

func (*Big) Reduce Uses

func (z *Big) Reduce() *Big

Reduce reduces a finite z to its most simplest form.

func (*Big) Rem Uses

func (z *Big) Rem(x, y *Big) *Big

Rem sets z to the remainder x % y. See QuoRem for more details.

func (*Big) Round Uses

func (z *Big) Round(n int) *Big

Round rounds z down to n digits of precision and returns z. The result is undefined if z is not finite. No rounding will occur if n <= 0. The result of Round will always be within the interval [⌊10**x⌋, z] where x = the precision of z.

Code:

a, _ := new(Big).SetString("1234")
b, _ := new(Big).SetString("54.4")
c, _ := new(Big).SetString("60")
d, _ := new(Big).SetString("0.0022")

fmt.Println(a.Round(2))
fmt.Println(b.Round(2))
fmt.Println(c.Round(5))
fmt.Println(d.Round(1))

Output:

1.2E+3
54
60
0.002

func (*Big) RoundToInt Uses

func (z *Big) RoundToInt() *Big

RoundToInt rounds z down to an integral value.

func (*Big) Scale Uses

func (x *Big) Scale() int

Scale returns x's scale.

func (*Big) Scan Uses

func (z *Big) Scan(state fmt.ScanState, verb rune) error

Scan implements fmt.Scanner.

func (*Big) Set Uses

func (z *Big) Set(x *Big) *Big

Set sets z to x and returns z. The result might be rounded depending on z's Context, and even if z == x.

func (*Big) SetBigMantScale Uses

func (z *Big) SetBigMantScale(value *big.Int, scale int) *Big

SetBigMantScale sets z to the given value and scale.

func (*Big) SetFloat Uses

func (z *Big) SetFloat(x *big.Float) *Big

SetFloat sets z to x and returns z.

func (*Big) SetFloat64 Uses

func (z *Big) SetFloat64(x float64) *Big

SetFloat64 sets z to exactly x.

func (*Big) SetInf Uses

func (z *Big) SetInf(signbit bool) *Big

SetInf sets z to -Inf if signbit is set or +Inf is signbit is not set, and returns z.

func (*Big) SetMantScale Uses

func (z *Big) SetMantScale(value int64, scale int) *Big

SetMantScale sets z to the given value and scale.

func (*Big) SetNaN Uses

func (z *Big) SetNaN(signal bool) *Big

SetNaN sets z to a signaling NaN if signal is true or quiet NaN otherwise and returns z. No conditions are raised.

func (*Big) SetRat Uses

func (z *Big) SetRat(x *big.Rat) *Big

SetRat sets z to to the possibly rounded value of x and return z.

func (*Big) SetScale Uses

func (z *Big) SetScale(scale int) *Big

SetScale sets z's scale to scale and returns z.

func (*Big) SetString Uses

func (z *Big) SetString(s string) (*Big, bool)

SetString sets z to the value of s, returning z and a bool indicating success. s must be a string in one of the following formats:

1.234
1234
1.234e+5
1.234E-5
0.000001234
Inf
NaN
qNaN
sNaN

Each value may be preceded by an optional sign, “-” or “+”. “Inf” and “NaN” map to “+Inf” and “qNaN”, respectively. NaN values may have optional diagnostic information, represented as trailing digits; for example, “NaN123”. These digits are otherwise ignored but are included for robustness.

func (*Big) SetUint64 Uses

func (z *Big) SetUint64(x uint64) *Big

SetUint64 is shorthand for SetMantScale(x, 0) for an unsigned integer.

func (*Big) Sign Uses

func (x *Big) Sign() int

Sign returns:

-1 if x <  0
 0 if x == 0
+1 if x >  0

The result is undefined if x is a NaN value.

func (*Big) Signbit Uses

func (x *Big) Signbit() bool

Signbit returns true if x is negative, negative infinity, negative zero, or negative NaN.

func (*Big) String Uses

func (x *Big) String() string

String returns the string representation of x. It's equivalent to the %s verb discussed in the Format method's documentation. Special cases depend on the OperatingMode.

func (*Big) Sub Uses

func (z *Big) Sub(x, y *Big) *Big

Sub sets z to x - y and returns z.

func (*Big) Uint64 Uses

func (x *Big) Uint64() (uint64, bool)

Uint64 returns x as a uint64, truncating towards zero. The returned boolean indicates whether the conversion to a uint64 was successful.

func (*Big) UnmarshalText Uses

func (z *Big) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Condition Uses

type Condition uint32

Condition is a bitmask value raised after or during specific operations. For example, dividing by zero is undefined so a DivisionByZero Condition flag will be set in the decimal's Context.

const (
    // Clamped occurs if the scale has been modified to fit the constraints of
    // the decimal representation.
    Clamped Condition = 1 << iota
    // ConversionSyntax occurs when a string is converted to a decimal and does
    // not have a valid syntax.
    ConversionSyntax
    // DivisionByZero occurs when division is attempted with a finite,
    // non-zero dividend and a divisor with a value of zero.
    DivisionByZero
    // DivisionImpossible occurs when the result of integer division would
    // contain too many digits (i.e. be longer than the specified precision).
    DivisionImpossible
    // DivisionUndefined occurs when division is attempted with in which both
    // the divided and divisor are zero.
    DivisionUndefined
    // Inexact occurs when the result of an operation (e.g. division) is not
    // exact, or when the Overflow/Underflow Conditions occur.
    Inexact
    // InsufficientStorage occurs when the system doesn't have enough storage
    // (i.e. memory) to store the decimal.
    InsufficientStorage
    // InvalidContext occurs when an invalid context was detected during an
    // operation. This might occur if, for example, an invalid RoundingMode was
    // passed to a Context.
    InvalidContext
    // InvalidOperation occurs when:
    //
    // 	- an operand to an operation is a signaling NaN
    // 	- an attempt is made to add or subtract infinities of opposite signs
    // 	- an attempt is made to multiply zero by an infinity of either sign
    // 	- an attempt is made to divide an infinity by an infinity
    // 	- the divisor for a remainder operation is zero
    // 	- the dividend for a remainder operation is an infinity
    // 	- either operand of the quantize operation is an infinity, or the result
    // 	  of a quantize operation would require greater precision than is
    // 	  available
    // 	- the operand of the ln or the log10 operation is less than zero
    // 	- the operand of the square-root operation has a sign of 1 and a
    // 	  non-zero coefficient
    // 	- both operands of the power operation are zero, or if the left-hand
    // 	  operand is less than zero and the right-hand operand does not have an
    // 	  integral value or is an infinity
    //
    InvalidOperation
    // Overflow occurs when the adjusted scale, after rounding, would be
    // greater than MaxScale. (Inexact and Rounded will also be raised.)
    Overflow
    // Rounded occurs when the result of an operation is rounded, or if an
    // Overflow/Underflow occurs.
    Rounded
    // Subnormal ocurs when the result of a conversion or operation is subnormal
    // (i.e. the adjusted scale is less than MinScale before any rounding).
    Subnormal
    // Underflow occurs when the result is inexact and the adjusted scale would
    // be smaller (more negative) than MinScale.
    Underflow
)

func (Condition) Error Uses

func (c Condition) Error() string

func (Condition) String Uses

func (c Condition) String() string

type Context Uses

type Context struct {
    // MaxScale overrides the MaxScale constant so long as it's in the range
    // (0, MaxScale].
    MaxScale int

    // MinScale overrides the MaxScale constant so long as it's in the range
    // [MinScale, 0).
    MinScale int

    // Precision is the Context's precision; that is, the maximum number of
    // significant digits that may result from any arithmetic operation.
    // Excluding any package-defined constants (e.g., ``UnlimitedPrecision''),
    // if precision is not in the range [1, MaxPrecision] operations might
    // result in an error. A precision of 0 will be interpreted as
    // DefaultPrecision. For example,
    //
    //   precision ==  4 // 4
    //   precision == -4 // error
    //   precision ==  0 // DefaultPrecision
    //   precision == 12 // 12
    //
    Precision int

    // Traps are a set of exceptional conditions that should result in an error.
    Traps Condition

    // Conditions are a set of the most recent exceptional conditions to occur
    // during an operation.
    Conditions Condition

    // RoundingMode determines how a decimal is rounded.
    RoundingMode RoundingMode

    // OperatingMode which dictates how the decimal operates under certain
    // conditions. See OperatingMode for more information.
    OperatingMode OperatingMode
}

Context is a per-decimal contextual object that governs specific operations.

func (Context) Add Uses

func (c Context) Add(z, x, y *Big) *Big

Add sets z to x + y and returns z.

func (Context) Err Uses

func (c Context) Err() error

Err returns non-nil if there are any trapped exceptional conditions.

func (Context) FMA Uses

func (c Context) FMA(z, x, y, u *Big) *Big

FMA sets z to (x * y) + u without any intermediate rounding.

func (Context) Mul Uses

func (c Context) Mul(z, x, y *Big) *Big

Mul sets z to x * y and returns z.

func (Context) Quantize Uses

func (c Context) Quantize(z *Big, n int) *Big

Quantize sets z to the number equal in value and sign to z with the scale, n.

func (Context) Quo Uses

func (c Context) Quo(z, x, y *Big) *Big

Quo sets z to x / y and returns z.

func (Context) QuoInt Uses

func (c Context) QuoInt(z, x, y *Big) *Big

QuoInt sets z to x / y with the remainder truncated. See QuoRem for more details.

func (Context) QuoRem Uses

func (c Context) QuoRem(z, x, y, r *Big) (*Big, *Big)

QuoRem sets z to the quotient x / y and r to the remainder x % y, such that x = z * y + r, and returns the pair (z, r).

func (Context) Reduce Uses

func (c Context) Reduce(z *Big) *Big

Reduce reduces a finite z to its most simplest form.

func (Context) Rem Uses

func (c Context) Rem(z, x, y *Big) *Big

Rem sets z to the remainder x % y. See QuoRem for more details.

func (Context) Round Uses

func (c Context) Round(z *Big) *Big

Round rounds z down to the Context's precision and returns z. The result is undefined if z is not finite. The result of Round will always be within the interval [⌊10**x⌋, z] where x = the precision of z.

func (Context) RoundToInt Uses

func (c Context) RoundToInt(z *Big) *Big

RoundToInt rounds z down to an integral value.

func (Context) Set Uses

func (c Context) Set(z, x *Big) *Big

Set sets z to x and returns z. The result might be rounded, even if z == x.

func (Context) SetString Uses

func (c Context) SetString(z *Big, s string) (*Big, bool)

SetString sets z to the value of s, returning z and a bool indicating success. See Big.SetString for valid formats.

func (Context) Sub Uses

func (c Context) Sub(z, x, y *Big) *Big

Sub sets z to x - y and returns z.

type ErrNaN Uses

type ErrNaN struct{ Msg string }

An ErrNaN is used when a decimal operation would lead to a NaN under IEEE-754 rules. An ErrNaN implements the error interface.

func (ErrNaN) Error Uses

func (e ErrNaN) Error() string

type OperatingMode Uses

type OperatingMode uint8

OperatingMode dictates how the decimal approaches specific non-numeric operations like conversions to strings and panicking on NaNs.

const (
    // GDA strictly adheres to the General Decimal Arithmetic Specification
    // Version 1.70. In particular:
    //
    //  - at does not panic
    //  - all arithmetic operations will be rounded down to the proper precision
    //    if necessary
    //  - it utilizes traps to set both Context.Err and Context.Conditions
    //  - its string forms of qNaN, sNaN, +Inf, and -Inf are "NaN", "sNaN",
    //    "Infinity", and "-Infinity", respectively
    //
    GDA OperatingMode = iota
    // Go adheres to typical Go idioms. In particular:
    //
    //  - it panics on NaN values
    //  - has lossless (i.e., without rounding) addition, subtraction, and
    //    multiplication
    //  - traps are ignored; it does not set Context.Err or Context.Conditions
    //  - its string forms of qNaN, sNaN, +Inf, and -Inf are "NaN", "NaN",
    //     "+Inf", and "-Inf", respectively
    //
    Go
)

func (OperatingMode) String Uses

func (i OperatingMode) String() string

type Payload Uses

type Payload uint64

Payload is a NaN value's payload.

func (Payload) String Uses

func (p Payload) String() string

type RoundingMode Uses

type RoundingMode uint8

RoundingMode determines how a decimal will be rounded.

const (
    ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven
    ToNearestAway                     // == IEEE 754-2008 roundTiesToAway
    ToZero                            // == IEEE 754-2008 roundTowardZero
    AwayFromZero                      // no IEEE 754-2008 equivalent
    ToNegativeInf                     // == IEEE 754-2008 roundTowardNegative
    ToPositiveInf                     // == IEEE 754-2008 roundTowardPositive

)

The following rounding modes are supported.

func (RoundingMode) String Uses

func (i RoundingMode) String() string

Directories

PathSynopsis
internal/arithPackage arith provides simple, primarily bit-specific, arithmetic operations.
internal/arith/checkedPackage checked implements basic checked arithmetic.
internal/cPackage c provides internal constants.
internal/test
mathPackage math implements various useful mathematical functions and constants.
math/debugPackage debug provides simple routines for debugging continued fractions.
miscPackage misc contains miscellaneous decimal routes.
sql/postgresPackage postgres provides a simple wrapper around a decimal.Big type, allowing it to be used in PostgreSQL queries.
suitePackage suite provides a simple API for parsing and using IBM Labs' "Floating-Point Test-Suite for IEEE"

Package decimal imports 16 packages (graph) and is imported by 9 packages. Updated 2018-08-09. Refresh now. Tools for package owners.