Documentation ¶
Overview ¶
Package decimal implements an arbitrary precision fixed-point decimal.
The zero-value of a Decimal is 0, as you would expect.
The best way to create a new Decimal is to use decimal.NewFromString, ex:
n, err := decimal.NewFromString("-123.4567") n.String() // output: "-123.4567"
To use Decimal as part of a struct:
type Struct struct { Number Decimal }
Note: This can "only" represent numbers with a maximum of 2^31 digits after the decimal point.
Index ¶
- Variables
- func RescalePair(d1 Decimal, d2 Decimal) (Decimal, Decimal)
- type CashRoundInterval
- type Decimal
- func Avg(first Decimal, rest ...Decimal) Decimal
- func Max(first Decimal, rest ...Decimal) Decimal
- func Min(first Decimal, rest ...Decimal) Decimal
- func New(value int64, exp int32) Decimal
- func NewFromBigInt(value *big.Int, exp int32) Decimal
- func NewFromFloat(value float64) Decimal
- func NewFromFloat32(value float32) Decimal
- func NewFromFloat32Safe(value float32) (Decimal, error)
- func NewFromFloatSafe(value float64) (Decimal, error)
- func NewFromFloatWithExponent(value float64, exp int32) Decimal
- func NewFromFloatWithExponentSafe(value float64, exp int32) (Decimal, error)
- func NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error)
- func NewFromInt(value int64) Decimal
- func NewFromInt32(value int32) Decimal
- func NewFromString(value string) (Decimal, error)
- func RequireFromString(value string) Decimal
- func Sum(first Decimal, rest ...Decimal) Decimal
- func (d Decimal) Abs() Decimal
- func (d Decimal) Add(d2 Decimal) Decimal
- func (d Decimal) Atan() Decimal
- func (d Decimal) BigFloat() *big.Float
- func (d Decimal) BigInt() *big.Int
- func (d Decimal) Ceil() Decimal
- func (d Decimal) Cmp(d2 Decimal) int
- func (d Decimal) Coefficient() *big.Int
- func (d Decimal) CoefficientInt64() int64
- func (d Decimal) Copy() Decimal
- func (d Decimal) Cos() Decimal
- func (d Decimal) Div(d2 Decimal) Decimal
- func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal
- func (d Decimal) Equal(d2 Decimal) bool
- func (d Decimal) Equals(d2 Decimal) bool
- func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error)
- func (d Decimal) ExpTaylor(precision int32) (Decimal, error)
- func (d Decimal) Exponent() int32
- func (d Decimal) Float64() (f float64, exact bool)
- func (d Decimal) Floor() Decimal
- func (d Decimal) GetOptions() *Options
- func (d *Decimal) GobDecode(data []byte) error
- func (d Decimal) GobEncode() ([]byte, error)
- func (d Decimal) GreaterThan(d2 Decimal) bool
- func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool
- func (d Decimal) InexactFloat64() float64
- func (d Decimal) IntPart() int64
- func (d Decimal) IsInteger() bool
- func (d Decimal) IsNegative() bool
- func (d Decimal) IsPositive() bool
- func (d Decimal) IsZero() bool
- func (d Decimal) LessThan(d2 Decimal) bool
- func (d Decimal) LessThanOrEqual(d2 Decimal) bool
- func (d Decimal) MarshalBinary() (data []byte, err error)
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) MarshalText() (text []byte, err error)
- func (d Decimal) Mod(d2 Decimal) Decimal
- func (d Decimal) Mul(d2 Decimal) Decimal
- func (d Decimal) Neg() Decimal
- func (d Decimal) NumDigits() int
- func (d Decimal) Pow(d2 Decimal) Decimal
- func (d Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal)
- func (d Decimal) Rat() *big.Rat
- func (d Decimal) Round(places int32) Decimal
- func (d Decimal) RoundBank(places int32) Decimal
- func (d Decimal) RoundCash(interval CashRoundInterval) Decimal
- func (d Decimal) RoundCeil(places int32) Decimal
- func (d Decimal) RoundDown(places int32) Decimal
- func (d Decimal) RoundFloor(places int32) Decimal
- func (d Decimal) RoundUp(places int32) Decimal
- func (d *Decimal) Scan(value interface{}) error
- func (d Decimal) SetOptions(options *Options) Decimal
- func (d Decimal) Shift(shift int32) Decimal
- func (d Decimal) Sign() int
- func (d Decimal) Sin() Decimal
- func (d Decimal) String() string
- func (d Decimal) StringFixed(places int32) string
- func (d Decimal) StringFixedBank(places int32) string
- func (d Decimal) StringFixedCash(interval CashRoundInterval) string
- func (d Decimal) StringScaled(exp int32) string
- func (d Decimal) Sub(d2 Decimal) Decimal
- func (d Decimal) Tan() Decimal
- func (d Decimal) Truncate(precision int32) Decimal
- func (d *Decimal) UnmarshalBinary(data []byte) error
- func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error
- func (d *Decimal) UnmarshalText(text []byte) error
- func (d Decimal) Value() (driver.Value, error)
- type NullDecimal
- func (d NullDecimal) MarshalJSON() ([]byte, error)
- func (d NullDecimal) MarshalText() (text []byte, err error)
- func (d *NullDecimal) Scan(value interface{}) error
- func (d *NullDecimal) UnmarshalJSON(decimalBytes []byte) error
- func (d *NullDecimal) UnmarshalText(text []byte) error
- func (d NullDecimal) Value() (driver.Value, error)
- type Options
- func (opt *Options) Avg(first Decimal, rest ...Decimal) Decimal
- func (opt *Options) GetDecimalSeparator() rune
- func (opt *Options) GetDivisionPrecision() int32
- func (opt *Options) GetExpMaxIterations() int
- func (opt *Options) GetMarshalJSONWithoutQuotes() bool
- func (opt *Options) GetParseUnicodeMinus() bool
- func (opt *Options) Max(first Decimal, rest ...Decimal) Decimal
- func (opt *Options) Min(first Decimal, rest ...Decimal) Decimal
- func (opt *Options) New(value int64, exp int32) Decimal
- func (opt *Options) NewFromBigInt(value *big.Int, exp int32) Decimal
- func (opt *Options) NewFromFloat(value float64) Decimal
- func (opt *Options) NewFromFloat32(value float32) Decimal
- func (opt *Options) NewFromFloat32Safe(value float32) (Decimal, error)
- func (opt *Options) NewFromFloatSafe(value float64) (Decimal, error)
- func (opt *Options) NewFromFloatWithExponent(value float64, exp int32) Decimal
- func (opt *Options) NewFromFloatWithExponentSafe(value float64, exp int32) (Decimal, error)
- func (opt *Options) NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error)
- func (opt *Options) NewFromInt(value int64) Decimal
- func (opt *Options) NewFromInt32(value int32) Decimal
- func (opt *Options) NewFromString(value string) (Decimal, error)
- func (opt *Options) RequireFromString(value string) Decimal
- func (opt *Options) SetDecimalSeparator(decimalSeparator rune) *Options
- func (opt *Options) SetDivisionPrecision(divisionPrecision int32) *Options
- func (opt *Options) SetExpMaxIterations(expMaxIterations int) *Options
- func (opt *Options) SetMarshalJSONWithoutQuotes(marshalJSONWithoutQuotes bool) *Options
- func (opt *Options) SetParseUnicodeMinus(parseUnicodeMinus bool) *Options
- func (opt *Options) Sum(first Decimal, rest ...Decimal) Decimal
- func (opt *Options) Zero() Decimal
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultOptions = &Options{ divisionPrecision: 16, marshalJSONWithoutQuotes: false, expMaxIterations: 1000, parseUnicodeMinus: true, }
Functions ¶
Types ¶
type CashRoundInterval ¶
type CashRoundInterval uint8
const CashRoundInterval10 CashRoundInterval = 10
const CashRoundInterval100 CashRoundInterval = 100
const CashRoundInterval25 CashRoundInterval = 25
const CashRoundInterval5 CashRoundInterval = 5
const CashRoundInterval50 CashRoundInterval = 50
type Decimal ¶
type Decimal struct {
// contains filtered or unexported fields
}
Decimal represents a fixed-point decimal. It is immutable. number = value * 10 ^ exp
var Zero Decimal
Zero constant, to make computations faster. Zero should never be compared with == or != directly, please use decimal.Equal or decimal.Cmp instead.
func NewFromFloat ¶
Example ¶
fmt.Println(NewFromFloat(123.123123123123).String()) fmt.Println(NewFromFloat(.123123123123123).String()) fmt.Println(NewFromFloat(-1e13).String())
Output: 123.123123123123 0.123123123123123 -10000000000000
func NewFromFloat32 ¶
Example ¶
fmt.Println(NewFromFloat32(123.123123123123).String()) fmt.Println(NewFromFloat32(.123123123123123).String()) fmt.Println(NewFromFloat32(-1e13).String())
Output: 123.12312 0.123123124 -10000000000000
func NewFromFloat32Safe ¶
func NewFromFloatSafe ¶
func NewFromFormattedString ¶
func NewFromInt ¶
func NewFromInt32 ¶
func NewFromString ¶
func RequireFromString ¶
func (Decimal) BigFloat ¶
BigFloat returns decimal as BigFloat. Be aware that casting decimal to BigFloat might cause a loss of precision.
func (Decimal) Cmp ¶
Cmp compares the numbers represented by d and d2 and returns:
-1 if d < d2 0 if d == d2 +1 if d > d2
func (Decimal) Coefficient ¶
Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()
func (Decimal) CoefficientInt64 ¶
CoefficientInt64 returns the coefficient of the decimal as int64. It is scaled by 10^Exponent() If coefficient cannot be represented in an int64, the result will be undefined.
func (Decimal) Copy ¶
Copy returns a copy of decimal with the same value and exponent, but a different pointer to value.
func (Decimal) Div ¶
Div returns d / d2. If it doesn't divide exactly, the result will have d.options.DivisionPrecision digits after the decimal point.
func (Decimal) DivRound ¶
DivRound divides and rounds to a given precision i.e. to an integer multiple of 10^(-precision)
for a positive quotient digit 5 is rounded up, away from 0 if the quotient is negative then digit 5 is rounded down, away from 0
Note that precision<0 is allowed as input.
func (Decimal) ExpHullAbrham ¶
ExpHullAbrham calculates the natural exponent of decimal (e to the power of d) using Hull-Abraham algorithm. OverallPrecision argument specifies the overall precision of the result (integer part + decimal part).
ExpHullAbrham is faster than ExpTaylor for small precision values, but it is much slower for large precision values.
Example:
NewFromFloat(26.1).ExpHullAbrham(2).String() // output: "220000000000" NewFromFloat(26.1).ExpHullAbrham(20).String() // output: "216314672147.05767284"
func (Decimal) ExpTaylor ¶
ExpTaylor calculates the natural exponent of decimal (e to the power of d) using Taylor series expansion. Precision argument specifies how precise the result must be (number of digits after decimal point). Negative precision is allowed.
ExpTaylor is much faster for large precision values than ExpHullAbrham.
Example:
d, err := NewFromFloat(26.1).ExpTaylor(2).String() d.String() // output: "216314672147.06" NewFromFloat(26.1).ExpTaylor(20).String() d.String() // output: "216314672147.05767284062928674083" NewFromFloat(26.1).ExpTaylor(-10).String() d.String() // output: "220000000000"
func (Decimal) Float64 ¶
Float64 returns the nearest float64 value for d and a bool indicating whether f represents d exactly. For more details, see the documentation for big.Rat.Float64
func (Decimal) GetOptions ¶
func (*Decimal) GobDecode ¶
GobDecode implements the gob.GobDecoder interface for gob serialization.
func (Decimal) GreaterThan ¶
GreaterThan (GT) returns true when d is greater than d2.
func (Decimal) GreaterThanOrEqual ¶
GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.
func (Decimal) InexactFloat64 ¶
InexactFloat64 returns the nearest float64 value for d. It doesn't indicate if the returned value represents d exactly.
func (Decimal) IsInteger ¶
IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false.
func (Decimal) LessThanOrEqual ¶
LessThanOrEqual (LTE) returns true when d is less than or equal to d2.
func (Decimal) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface.
func (Decimal) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (Decimal) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface for XML serialization.
func (Decimal) NumDigits ¶
NumDigits returns the number of digits of the decimal coefficient (d.Value) Note: Current implementation is extremely slow for large decimals and/or decimals with large fractional part
func (Decimal) QuoRem ¶
QuoRem does division with remainder d.QuoRem(d2,precision) returns quotient q and remainder r such that
d = d2 * q + r, q an integer multiple of 10^(-precision) 0 <= r < abs(d2) * 10 ^(-precision) if d>=0 0 >= r > -abs(d2) * 10 ^(-precision) if d<0
Note that precision<0 is allowed as input.
func (Decimal) Round ¶
Round rounds the decimal to places decimal places. If places < 0, it will round the integer part to the nearest 10^(-places).
Example:
NewFromFloat(5.45).Round(1).String() // output: "5.5" NewFromFloat(545).Round(-1).String() // output: "550"
func (Decimal) RoundBank ¶
RoundBank rounds the decimal to places decimal places. If the final digit to round is equidistant from the nearest two integers the rounded value is taken as the even number
If places < 0, it will round the integer part to the nearest 10^(-places).
Examples:
NewFromFloat(5.45).RoundBank(1).String() // output: "5.4" NewFromFloat(545).RoundBank(-1).String() // output: "540" NewFromFloat(5.46).RoundBank(1).String() // output: "5.5" NewFromFloat(546).RoundBank(-1).String() // output: "550" NewFromFloat(5.55).RoundBank(1).String() // output: "5.6" NewFromFloat(555).RoundBank(-1).String() // output: "560"
func (Decimal) RoundCash ¶
func (d Decimal) RoundCash(interval CashRoundInterval) Decimal
RoundCash aka Cash/Penny/öre rounding rounds decimal to a specific interval. The amount payable for a cash transaction is rounded to the nearest multiple of the minimum currency unit available. The following intervals are available: 5, 10, 25, 50 and 100; any other number throws a panic.
5: 5 cent rounding 3.43 => 3.45 10: 10 cent rounding 3.45 => 3.50 (5 gets rounded up) 25: 25 cent rounding 3.41 => 3.50 50: 50 cent rounding 3.75 => 4.00 100: 100 cent rounding 3.50 => 4.00
For more details: https://en.wikipedia.org/wiki/Cash_rounding
func (Decimal) RoundCeil ¶
RoundCeil rounds the decimal towards +infinity.
Example:
NewFromFloat(545).RoundCeil(-2).String() // output: "600" NewFromFloat(500).RoundCeil(-2).String() // output: "500" NewFromFloat(1.1001).RoundCeil(2).String() // output: "1.11" NewFromFloat(-1.454).RoundCeil(1).String() // output: "-1.5"
func (Decimal) RoundDown ¶
RoundDown rounds the decimal towards zero.
Example:
NewFromFloat(545).RoundDown(-2).String() // output: "500" NewFromFloat(-500).RoundDown(-2).String() // output: "-500" NewFromFloat(1.1001).RoundDown(2).String() // output: "1.1" NewFromFloat(-1.454).RoundDown(1).String() // output: "-1.5"
func (Decimal) RoundFloor ¶
RoundFloor rounds the decimal towards -infinity.
Example:
NewFromFloat(545).RoundFloor(-2).String() // output: "500" NewFromFloat(-500).RoundFloor(-2).String() // output: "-500" NewFromFloat(1.1001).RoundFloor(2).String() // output: "1.1" NewFromFloat(-1.454).RoundFloor(1).String() // output: "-1.4"
func (Decimal) RoundUp ¶
RoundUp rounds the decimal away from zero.
Example:
NewFromFloat(545).RoundUp(-2).String() // output: "600" NewFromFloat(500).RoundUp(-2).String() // output: "500" NewFromFloat(1.1001).RoundUp(2).String() // output: "1.11" NewFromFloat(-1.454).RoundUp(1).String() // output: "-1.4"
func (Decimal) SetOptions ¶
func (Decimal) Shift ¶
Shift shifts the decimal in base 10. It shifts left when shift is positive and right if shift is negative. In simpler terms, the given value for shift is added to the exponent of the decimal.
func (Decimal) String ¶
String returns the string representation of the decimal with the fixed point.
Example:
d := New(-12345, -3) println(d.String())
Output:
-12.345
func (Decimal) StringFixed ¶
StringFixed returns a rounded fixed-point string with places digits after the decimal point.
Example:
NewFromFloat(0).StringFixed(2) // output: "0.00" NewFromFloat(0).StringFixed(0) // output: "0" NewFromFloat(5.45).StringFixed(0) // output: "5" NewFromFloat(5.45).StringFixed(1) // output: "5.5" NewFromFloat(5.45).StringFixed(2) // output: "5.45" NewFromFloat(5.45).StringFixed(3) // output: "5.450" NewFromFloat(545).StringFixed(-1) // output: "550"
func (Decimal) StringFixedBank ¶
StringFixedBank returns a banker rounded fixed-point string with places digits after the decimal point.
Example:
NewFromFloat(0).StringFixedBank(2) // output: "0.00" NewFromFloat(0).StringFixedBank(0) // output: "0" NewFromFloat(5.45).StringFixedBank(0) // output: "5" NewFromFloat(5.45).StringFixedBank(1) // output: "5.4" NewFromFloat(5.45).StringFixedBank(2) // output: "5.45" NewFromFloat(5.45).StringFixedBank(3) // output: "5.450" NewFromFloat(545).StringFixedBank(-1) // output: "540"
func (Decimal) StringFixedCash ¶
func (d Decimal) StringFixedCash(interval CashRoundInterval) string
StringFixedCash returns a Swedish/Cash rounded fixed-point string. For more details see the documentation at function RoundCash.
func (Decimal) StringScaled ¶
StringScaled first scales the decimal then calls .String() on it. NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.
func (Decimal) Truncate ¶
Truncate truncates off digits from the number, without rounding.
NOTE: precision is the last digit that will not be truncated (must be >= 0).
Example:
decimal.NewFromString("123.456").Truncate(2).String() // "123.45"
func (*Decimal) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation is already used when encoding to text, this method stores that string as []byte
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface.
func (*Decimal) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.
type NullDecimal ¶
NullDecimal represents a nullable decimal with compatibility for scanning null values from the database.
func NewNullDecimal ¶
func NewNullDecimal(d Decimal) NullDecimal
func (NullDecimal) MarshalJSON ¶
func (d NullDecimal) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
func (NullDecimal) MarshalText ¶
func (d NullDecimal) MarshalText() (text []byte, err error)
MarshalText implements the encoding.TextMarshaler interface for XML serialization.
func (*NullDecimal) Scan ¶
func (d *NullDecimal) Scan(value interface{}) error
Scan implements the sql.Scanner interface for database deserialization.
func (*NullDecimal) UnmarshalJSON ¶
func (d *NullDecimal) UnmarshalJSON(decimalBytes []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
func (*NullDecimal) UnmarshalText ¶
func (d *NullDecimal) UnmarshalText(text []byte) error
UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
func (*Options) GetDecimalSeparator ¶
func (*Options) GetDivisionPrecision ¶
func (*Options) GetExpMaxIterations ¶
func (*Options) GetMarshalJSONWithoutQuotes ¶
func (*Options) GetParseUnicodeMinus ¶
func (*Options) Max ¶
Max returns the largest Decimal that was passed in the arguments.
To call this function with an array, you must do:
Max(arr[0], arr[1:]...)
This makes it harder to accidentally call Max with 0 arguments.
func (*Options) Min ¶
Min returns the smallest Decimal that was passed in the arguments.
To call this function with an array, you must do:
Min(arr[0], arr[1:]...)
This makes it harder to accidentally call Min with 0 arguments.
func (*Options) NewFromBigInt ¶
NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp
func (*Options) NewFromFloat ¶
NewFromFloat converts a float64 to Decimal.
The converted number will contain the number of significant digits that can be represented in a float with reliable roundtrip. This is typically 15 digits, but may be more in some cases. See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.
For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.
NOTE: this will panic on NaN, +/-inf
func (*Options) NewFromFloat32 ¶
NewFromFloat32 converts a float32 to Decimal.
The converted number will contain the number of significant digits that can be represented in a float with reliable roundtrip. This is typically 6-8 digits depending on the input. See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.
For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.
NOTE: this will panic on NaN, +/-inf
func (*Options) NewFromFloat32Safe ¶
NewFromFloat32Safe is a version of NewFromFloat32 that returns an error instead of panic in case of NaN, +/-inf
func (*Options) NewFromFloatSafe ¶
NewFromFloatSafe is a version of NewFromFloat that returns error in case of NaN, +/-inf instead of panic
func (*Options) NewFromFloatWithExponent ¶
NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary number of fractional digits.
Example:
NewFromFloatWithExponent(123.456, -2).String() // output: "123.46"
func (*Options) NewFromFloatWithExponentSafe ¶
func (*Options) NewFromFormattedString ¶
func (opt *Options) NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error)
NewFromFormattedString returns a new Decimal from a formatted string representation. The second argument - replRegexp, is a regular expression that is used to find characters that should be removed from given decimal string representation. All matched characters will be replaced with an empty string.
Example:
r := regexp.MustCompile("[$,]") d1, err := NewFromFormattedString("$5,125.99", r) r2 := regexp.MustCompile("[_]") d2, err := NewFromFormattedString("1_000_000", r2) r3 := regexp.MustCompile("[USD\\s]") d3, err := NewFromFormattedString("5000 USD", r3)
func (*Options) NewFromInt ¶
NewFromInt converts a int64 to Decimal.
Example:
NewFromInt(123).String() // output: "123" NewFromInt(-10).String() // output: "-10"
func (*Options) NewFromInt32 ¶
NewFromInt32 converts a int32 to Decimal.
Example:
NewFromInt(123).String() // output: "123" NewFromInt(-10).String() // output: "-10"
func (*Options) NewFromString ¶
NewFromString returns a new Decimal from a string representation. Trailing zeroes are not trimmed.
Example:
d, err := NewFromString("-123.45") d2, err := NewFromString(".0001") d3, err := NewFromString("1.47000")
func (*Options) RequireFromString ¶
RequireFromString returns a new Decimal from a string representation or panics if NewFromString would have returned an error.
Example:
d := RequireFromString("-123.45") d2 := RequireFromString(".0001")