Arbitrary-precision fixed-point decimal numbers for Go, avoiding floating-point precision issues with support for arithmetic, rounding, serialization, and database integration.
Package-level variables that control global behavior of arithmetic operations and serialization. These are package-level mutable variables and affect all operations.
Controls the number of decimal places in division results when the division is not exact.
// DivisionPrecision is the number of decimal places in the result when it
// doesn't divide exactly. Default: 16.
var DivisionPrecision = 16Usage:
import "github.com/shopspring/decimal"
// Default behavior (16 places)
d1 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
d1.String() // "0.6666666666666667"
// Reduce precision globally
decimal.DivisionPrecision = 4
d2 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
d2.String() // "0.6667"Controls the maximum precision (digits after decimal point) when calculating decimal power with negative exponents. Applies to Pow, PowInt32, and PowBigInt methods. Does not constrain PowWithPrecision.
// PowPrecisionNegativeExponent specifies the maximum precision of the result
// (digits after decimal point) when calculating decimal power with negative exponent.
// Default: 16.
var PowPrecisionNegativeExponent = 16Usage:
d1, _ := decimal.NewFromFloat(15.2).PowInt32(-2)
d1.String() // "0.0043282548476454" (16 places)
decimal.PowPrecisionNegativeExponent = 24
d2, _ := decimal.NewFromFloat(15.2).PowInt32(-2)
d2.String() // "0.004328254847645429362881" (24 places)Controls whether Decimal marshals to JSON as a quoted string (default) or as a raw number.
// MarshalJSONWithoutQuotes controls JSON marshaling output format.
// Default: false (marshal as quoted string).
// WARNING: Setting to true risks silent precision loss in JSON parsers
// that use IEEE 754 double-precision floats (e.g., JavaScript).
var MarshalJSONWithoutQuotes = falseUsage:
d := decimal.NewFromFloat(3.14)
// Default (false): marshals as quoted string
data, _ := d.MarshalJSON() // `"3.14"`
// Enable number marshaling
decimal.MarshalJSONWithoutQuotes = true
data, _ = d.MarshalJSON() // `3.14`Limits the maximum iterations for natural exponent calculation using Hull-Abraham method.
// ExpMaxIterations specifies the maximum number of iterations needed to
// calculate precise natural exponent value using ExpHullAbrham method.
// Default: 1000.
var ExpMaxIterations = 1000A pre-created zero value for performance in comparisons. Never use == or != directly on Decimal values; use .Equal() or .Cmp() instead.
// Zero constant for faster computations.
// Use decimal.Equal or decimal.Cmp for comparisons, not == or !=.
var Zero = New(0, 1)Usage:
d := decimal.NewFromFloat(0)
// Correct comparison
d.Equal(decimal.Zero) // true
d.Cmp(decimal.Zero) // 0
// Also correct
d.IsZero() // trueInstall with Tessl CLI
npx tessl i tessl/golang-github-com-shopspring--decimal@1.4.1