Documentation
¶
Overview ¶
Package decimal provides a high-performance, zero-allocation fixed-point decimal type (and companion Weight / Length types with unit support) packed in a single 8-byte int64. See README.md for an overview and BINARY_FORMAT.md for the open wire-format specification.
Index ¶
- Constants
- Variables
- 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 NewFromBytes(value []byte) (Decimal, error)
- func NewFromFloat(value float64) Decimal
- func NewFromFloat32(value float32) Decimal
- func NewFromFloat64Exact(value float64, exact bool) Decimal
- func NewFromFloatWithExponent(value float64, exp int32) Decimal
- 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 NewFromUint64(value uint64) Decimal
- func RequireFromString(value string) Decimal
- func Sum(first Decimal, rest ...Decimal) Decimal
- func (d Decimal) Abs() Decimal
- func (d1 Decimal) Add(d2 Decimal) Decimal
- func (d Decimal) Atan() Decimal
- func (d Decimal) BytesTo(b []byte) []byte
- func (d Decimal) BytesToFixed(b []byte, places int32) []byte
- func (d Decimal) BytesToFixedBank(b []byte, places int32) []byte
- func (d Decimal) Ceil() Decimal
- func (d1 Decimal) Cmp(d2 Decimal) int
- func (d1 Decimal) Compare(d2 Decimal) int
- func (d Decimal) Copy() Decimal
- func (d Decimal) Cos() Decimal
- func (d1 Decimal) Div(d2 Decimal) Decimal
- func (d1 Decimal) DivRound(d2 Decimal, precision int32) Decimal
- func (d1 Decimal) Equal(d2 Decimal) bool
- func (d Decimal) Exponent() int32
- func (d Decimal) Float64() (f float64, exact bool)
- func (d Decimal) Floor() Decimal
- func (d *Decimal) GobDecode(data []byte) error
- func (d Decimal) GobEncode() ([]byte, error)
- func (d1 Decimal) GreaterThan(d2 Decimal) bool
- func (d1 Decimal) GreaterThanOrEqual(d2 Decimal) bool
- func (d Decimal) IfNull(defaultValue Decimal) Decimal
- func (d Decimal) InexactFloat64() float64
- func (d Decimal) Int64() (i int64)
- func (d Decimal) IntPart() (i int64)
- func (d Decimal) IntPartErr() (int64, error)
- func (d Decimal) IsExact() bool
- func (d Decimal) IsExactlyZero() bool
- func (d Decimal) IsInfinite() bool
- func (d Decimal) IsInteger() bool
- func (d Decimal) IsNaN() bool
- func (d Decimal) IsNegative() bool
- func (d Decimal) IsNull() bool
- func (d Decimal) IsPositive() bool
- func (d Decimal) IsSet() bool
- func (d Decimal) IsZero() bool
- func (d1 Decimal) LessThan(d2 Decimal) bool
- func (d1 Decimal) LessThanOrEqual(d2 Decimal) bool
- func (d Decimal) Ln(precision int32) Decimal
- func (d Decimal) Mantissa() int64
- func (d Decimal) MarshalBinary() (data []byte, err error)
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) MarshalText() (text []byte, err error)
- func (d1 Decimal) Mod(d2 Decimal) Decimal
- func (d1 Decimal) Mul(d2 Decimal) Decimal
- func (d Decimal) Neg() Decimal
- func (d Decimal) NumDigits() int
- func (d1 Decimal) Pow(d2 Decimal) Decimal
- func (d Decimal) PowInt32(exp int32) (Decimal, error)
- func (d1 Decimal) PowWithPrecision(d2 Decimal, precision int32) (Decimal, error)
- func (d1 Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal)
- func (d Decimal) Round(places int32) Decimal
- func (d Decimal) RoundBank(places int32) Decimal
- func (d Decimal) RoundCash(interval uint8) 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{}) (err error)
- func (d Decimal) Shift(shift int32) Decimal
- func (d Decimal) Sign() int
- func (d Decimal) Sin() Decimal
- func (d Decimal) Sqrt() 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 uint8) string
- func (d1 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(b []byte) error
- func (d *Decimal) UnmarshalText(text []byte) error
- func (d Decimal) Value() (driver.Value, error)
- type Length
- func (l Length) Abs() Length
- func (l1 Length) Add(l2 Length) Length
- func (l Length) BytesTo(b []byte) []byte
- func (l1 Length) Compare(l2 Length) int
- func (l Length) Div(d Decimal) Length
- func (l1 Length) GreaterThan(l2 Length) bool
- func (l1 Length) GreaterThanOrEqual(l2 Length) bool
- func (l Length) IfNull(defaultValue Length) Length
- func (l Length) IsExact() bool
- func (l Length) IsExactlyZero() bool
- func (l Length) IsInfinite() bool
- func (l Length) IsNaN() bool
- func (l Length) IsNegative() bool
- func (l Length) IsNull() bool
- func (l Length) IsPositive() bool
- func (l Length) IsSet() bool
- func (l Length) IsZero() bool
- func (l1 Length) LessThan(l2 Length) bool
- func (l1 Length) LessThanOrEqual(l2 Length) bool
- func (l Length) MarshalBinary() (data []byte, err error)
- func (l Length) MarshalJSON() ([]byte, error)
- func (l Length) MarshalText() (text []byte, err error)
- func (l Length) Mul(d Decimal) Length
- func (l Length) Sign() int
- func (l Length) String() string
- func (l1 Length) Sub(l2 Length) Length
- func (l Length) Unit() string
- func (l *Length) UnmarshalBinary(data []byte) error
- func (l *Length) UnmarshalJSON(b []byte) error
- func (l *Length) UnmarshalText(text []byte) error
- type Weight
- func (w Weight) Abs() Weight
- func (w1 Weight) Add(w2 Weight) Weight
- func (w Weight) BytesTo(b []byte) []byte
- func (w1 Weight) Compare(w2 Weight) int
- func (w Weight) Div(d Decimal) Weight
- func (w1 Weight) GreaterThan(w2 Weight) bool
- func (w1 Weight) GreaterThanOrEqual(w2 Weight) bool
- func (w Weight) IfNull(defaultValue Weight) Weight
- func (w Weight) IsExact() bool
- func (w Weight) IsExactlyZero() bool
- func (w Weight) IsInfinite() bool
- func (w Weight) IsNaN() bool
- func (w Weight) IsNegative() bool
- func (w Weight) IsNull() bool
- func (w Weight) IsPositive() bool
- func (w Weight) IsSet() bool
- func (w Weight) IsZero() bool
- func (w1 Weight) LessThan(w2 Weight) bool
- func (w1 Weight) LessThanOrEqual(w2 Weight) bool
- func (w Weight) MarshalBinary() (data []byte, err error)
- func (w Weight) MarshalJSON() ([]byte, error)
- func (w Weight) MarshalText() (text []byte, err error)
- func (w Weight) Mul(d Decimal) Weight
- func (w Weight) Sign() int
- func (w Weight) String() string
- func (w1 Weight) Sub(w2 Weight) Weight
- func (w Weight) Unit() string
- func (w *Weight) UnmarshalBinary(data []byte) error
- func (w *Weight) UnmarshalJSON(b []byte) error
- func (w *Weight) UnmarshalText(text []byte) error
Constants ¶
const ( // LengthMaxInt constant is the maximal int64 value that can be safely saved as Length with exponent still 0. // LengthMaxInt is as well the maximum value of mantissa of Length and the bitmask to extract mantissa value of a Length. LengthMaxInt = 0x001fffffffffffff )
const ( // WeightMaxInt constant is the maximal int64 value that can be safely saved as Weight with exponent still 0. // WeightMaxInt is as well the maximum value of mantissa of Weight and the bitmask to extract mantissa value of a Weight. WeightMaxInt = 0x001fffffffffffff )
Variables ¶
var ( // ErrOutOfRange can occurs when converting a decimal to a int or int64 as integer may not hold the integer part of the decimal value. ErrOutOfRange = errors.New("out of range") // ErrSyntax can occurs when converting a string to a decimal. ErrSyntax = errors.New("invalid syntax") // ErrUnitSyntax occurs when unit is not recognized. ErrUnitSyntax = errors.New("invalid unit syntax") // ErrFormatcan occurs when decoding a binary to a decimal. ErrFormat = errors.New("invalid format") // DivisionPrecision has the number of decimal places in the result when it doesn't divide exactly. DivisionPrecision = 16 // PowPrecisionNegativeExponent has the maximum precision (digits after the decimal point) of the result of PowInt32 when the exponent is negative. PowPrecisionNegativeExponent = 16 )
Functions ¶
This section is empty.
Types ¶
type Decimal ¶
type Decimal int64
Decimal represents a fixed-point decimal hold as a 64 bits integer integer value between -144115188075855871 and 144115188075855871 (or MaxInt) can safely be used as Decimal, example :
var a Decimal = -1001 // a is a Decimal of integer value -1001
if a.Div(1000).Sub(1).Div(5).Mul(14000).Add(14).Div(-28) == 1000 {
fmt.Printf("ok: (((a/1000)-1)*14000+14)/-28 == 1000\n") // will print "ok: (((a/1000)-1)*14000+14)/-28 == 1000"
}
Note 0 is unitialized Decimal and its value for calculation is 0 like Zero which is initialized 0 Note Zero is now the same int64 value as types.IntZero, so casting an types.IntZero to Decimal is safe provided is absolute value is not too high Note you need to use Decimal method for calculation, you cannot use + - * / or any other operators unless Decimal is a real non-zero integer value Unitialized Decimal is useful when using JSON marshaling/unmarshaling.
Note Decimal does not follow IEEE 754 decimal floating point 64 bits representation. This is because Decimal is compatible with a large range of int64 values as described above for ease of use and use extended mantissa of 57 bits instead of 50 bits for IEEE 754 decimal floating point, thus providing only 17 significant digits (in fact a little more than float64)
const ( // Null constant is the default value of a decimal left unitialized. // A decimal can be directly initialized with 0 and it will be empty. // Null can be safely compared with == or != directly, you may use decimal.IsNull or any other decimal method to check if it is null. // Any operation on Decimal will never return a Null. // Null is seen as 0 for any operation Null = 0 // MaxInt constant is the maximal int64 value that can be safely saved as Decimal with exponent still 0. // MaxInt is as well the maximum value of mantissa of Decimal and the bitmask to extract mantissa value of a Decimal. MaxInt = 0x01ffffffffffffff // Zero constant is not empty zero Decimal value. // A decimal can be directly initialized with Zero and it will be not empty, but zero. // Zero can be safely compared with == or != directly to check for not empty zero decimal value. // But you need to use d.IsExactlyZero() to test if decimal d is zero or null. Zero Decimal = math.MinInt64 // NearZero represents a decimal value too close to 0 but not equal to zero, its sign is undefined. // NearPositiveZero and NearNegativeZero represents a signed decimal value too close to 0 but not equal to zero, its sign has been kept. // They can be safely compared with == or != directly but -NearZero may occurs and should be "seen" as NearZero NearZero Decimal = Zero | loss NearPositiveZero Decimal = 0x6000000000000000 NearNegativeZero Decimal = -NearPositiveZero // PositiveInfinity and NegativeInfinity are constants that represents decimal too big to be represented as a decimal value. // They can safely be compared with == or != directly to check for infinite value. PositiveInfinity Decimal = 0x5e00000000000000 NegativeInfinity Decimal = -PositiveInfinity // NaN represent a decimal which do not represents any more a number. // NaN should never be compared with == or != directly as they are multiple representation of such "nan" internally (search for NaN boxing for more info). // Use IsNaN method to check if a decimal is not a number. NaN Decimal = 0x4200000000000000 )
func New ¶
New returns a new fixed-point decimal, value * 10 ^ exp, compatible with shopspring/decimal New function.
func NewFromBytes ¶
NewFromBytes returns a new Decimal from a slice of bytes representation.
func NewFromFloat ¶
NewFromFloat converts a float64 to Decimal.
func NewFromFloat32 ¶
NewFromFloat32 converts a float32 to Decimal.
func NewFromFloat64Exact ¶
NewFromFloat64Exact converts a float64 to Decimal. When exact is false, the loss bit is forced on the result.
func NewFromFloatWithExponent ¶
NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary number of fractional digits.
func NewFromFormattedString ¶ added in v1.0.0
NewFromFormattedString returns a new Decimal from a formatted string representation. Characters matching replRegexp are stripped from value before parsing.
Useful to consume locale-formatted numbers, e.g. "$1,234.56" or " 9 876.54 €":
r := regexp.MustCompile(`[$,€\s]`)
d, err := NewFromFormattedString("$1,234.56", r) // d = 1234.56
Note: the function only removes characters; if you need to swap a comma decimal separator for a dot, preprocess value yourself before calling.
func NewFromInt32 ¶
NewFromInt32 converts a int32 to Decimal.
func NewFromString ¶
NewFromString returns a new Decimal from a string representation.
Example:
d, err := NewFromString("-123.45")
d2, err := NewFromString(".0001")
d3, err := NewFromString("1.47000")
d4, err := NewFromString("3.14e15")
func NewFromUint64 ¶
NewFromUint64 converts uint64 to Decimal.
func 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")
func Sum ¶
Sum returns the combined total of the provided first and rest Decimals using improved Kahan–Babuška Neumaier algorithm, see https://en.wikipedia.org/wiki/Kahan_summation_algorithm
Example:
d := Sum(1, RequireFromString("1e30"), 1, RequireFromString("-1e30"))
func (Decimal) BytesTo ¶ added in v0.5.0
BytesTo appends the string representation of the decimal to a slice of byte, if the decimal is Null it appends 0.
func (Decimal) BytesToFixed ¶ added in v0.5.0
func (Decimal) BytesToFixedBank ¶ added in v0.5.0
func (Decimal) Compare ¶
Compare compares the numbers represented by d1 and d2 without taking into account lost precision and returns:
-1 if d1 < d2 0 if d1 == d2 +1 if d1 > d2
func (Decimal) Copy ¶ added in v0.6.0
Copy returns a copy of the decimal. As Decimal is an immutable int64, the returned value has the same bit pattern. Provided for API compatibility with shopspring/decimal.
func (Decimal) Div ¶
Div returns d1 / d2. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point and loss bit will be set.
func (Decimal) DivRound ¶ added in v0.6.0
DivRound divides d1 by d2 and rounds the result to a given precision (an integer multiple of 10^(-precision)).
Rounding follows the package Round semantics. Negative precision is allowed.
func (Decimal) Equal ¶
Equal returns whether d1 == d2 without taking care of loss bit. The values Null, Zero, NearZero, NearPositiveZero and NearNegativeZero are equals.
func (Decimal) Exponent ¶ added in v0.0.5
Exponent returns the exponent, or scale component of the decimal.
func (Decimal) Float64 ¶
Float64 returns the nearest float64 value for d and a bool indicating whether f may represents d exactly.
func (*Decimal) GobDecode ¶
GobDecode implements the gob.GobDecoder interface for gob serialization.
func (Decimal) GreaterThan ¶ added in v0.3.0
GreaterThan returns true when d1 is greater than d2 (d1 > d2).
func (Decimal) GreaterThanOrEqual ¶ added in v0.3.0
GreaterThanOrEqual returns true when d1 is greater than or equal to d2 (d1 >= d2).
func (Decimal) InexactFloat64 ¶
InexactFloat64 returns the nearest float64 value for d.
func (Decimal) Int64 ¶
Int64 returns the integer component of the decimal, this method is a synonym of IntPart
func (Decimal) IntPartErr ¶
IntPartErr return the integer component of the decimal and an eventual out-of-range error of conversion.
func (Decimal) IsExact ¶
IsExact return true if a decimal has its loss bit not set, ie it has not lost its precision during computation or conversion.
func (Decimal) IsExactlyZero ¶
IsExactlyZero return
true if d == Null or d == Zero false if d == ~0 or d == -~0 or d == +~0 false if d < 0 false if d > 0
func (Decimal) IsInfinite ¶
IsInfinite return
true if a d == +Inf or d == -Inf false in any other case
func (Decimal) IsNegative ¶
IsNegative return
true if d < 0 or d == ~-0 false if d == Null or d == Zero or d == ~0 false if d > 0
func (Decimal) IsNull ¶
IsNull return
true if d == Null false if d == 0 false if d == ~0 or d == -~0 or d == +~0 false if d < 0 false if d > 0
func (Decimal) IsPositive ¶
IsPositive return
true if d > 0 or d == ~+0 false if d == Null or d == Zero or d == ~0 false if d < 0 or d == ~-0 false if d is NaN
func (Decimal) IsSet ¶
IsSet return
false if d == Null true if d == 0 true if d == ~0 or d == -~0 or d == +~0 true if d < 0 true if d > 0
func (Decimal) IsZero ¶
IsZero return
true if d == Null or d == Zero true if d == ~0 or d == -~0 or d == +~0 false if d < 0 false if d > 0
func (Decimal) LessThanOrEqual ¶
LessThanOrEqual returns true when d1 is less than or equal to d2 (d1 <= d2).
func (Decimal) Ln ¶
Ln calculates natural logarithm of d. Precision argument specifies how precise the result must be (number of digits after decimal point). Negative precision is allowed.
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 ¶ added in v0.6.0
NumDigits returns the number of digits of the decimal mantissa in base 10. Mantissa is only normalized (trailing zeros dropped) when its absolute value would otherwise exceed MaxInt or its exponent would be out of range, so 100 is kept as mantissa=100 (NumDigits=3) while 10^18 is normalized to mantissa=1, exp=18 (NumDigits=1). Null, Zero, NearZero, NearPositiveZero, NearNegativeZero, +Inf, -Inf and NaN return 1.
func (Decimal) PowInt32 ¶ added in v0.6.0
PowInt32 returns d to the power of exp using fast exponentiation by squaring (so without going through float64 like Pow). When exp is negative, the result is rounded to PowPrecisionNegativeExponent digits after the decimal point.
Returns an error only when d is zero and exp is zero (indeterminate form 0**0).
Examples:
NewFromFloat(4).PowInt32(4) // 256, nil NewFromFloat(3.13).PowInt32(5) // 300.4150512793, nil NewFromFloat(15.2).PowInt32(-2) // 0.0043282548476454, nil
func (Decimal) PowWithPrecision ¶
PowWithPrecision returns d to the power of d2. Precision parameter specifies minimum precision of the result (digits after decimal point). Returned decimal is not rounded to 'precision' places after decimal point.
func (Decimal) QuoRem ¶
QuoRem does division with remainder d1.QuoRem(d2,precision) returns quotient q and remainder r such that
d1 = d2 * q + r, q an integer multiple of 10^(-precision) 0 <= r < abs(d2) * 10 ^(-precision) if d1 >= 0 0 >= r > -abs(d2) * 10 ^(-precision) if d1 < 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).
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 ¶ added in v0.6.0
RoundCash rounds the decimal to the nearest multiple of the given Cash interval (in units of 10^(-2), or hundredths). Valid intervals are 5, 10, 25, 50 and 100 (Swedish/cash rounding). Panics for any other interval.
Examples:
NewFromFloat(3.43).RoundCash(5) // 3.45 NewFromFloat(3.45).RoundCash(10) // 3.5 NewFromFloat(3.41).RoundCash(25) // 3.5 NewFromFloat(3.75).RoundCash(50) // 4 NewFromFloat(3.50).RoundCash(100) // 4
func (Decimal) RoundDown ¶ added in v0.6.0
RoundDown rounds the decimal towards zero. If places < 0, it will round the integer part to the nearest 10^(-places).
Examples:
NewFromFloat(545).RoundDown(-2).String() // "500" NewFromFloat(-500).RoundDown(-2).String() // "-500" NewFromFloat(1.1001).RoundDown(2).String() // "1.1" NewFromFloat(-1.454).RoundDown(1).String() // "-1.4"
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.5"
func (Decimal) RoundUp ¶ added in v0.6.0
RoundUp rounds the decimal away from zero. If places < 0, it will round the integer part to the nearest 10^(-places).
Examples:
NewFromFloat(545).RoundUp(-2).String() // "600" NewFromFloat(500).RoundUp(-2).String() // "500" NewFromFloat(1.1001).RoundUp(2).String() // "1.11" NewFromFloat(-1.454).RoundUp(1).String() // "-1.5"
func (Decimal) Shift ¶ added in v0.6.0
Shift shifts the decimal in base 10. Positive shift moves left (multiply by 10^shift), negative shift moves right. In other words, the value of shift is added to the exponent of the decimal.
Examples:
d, _ := NewFromString("123.45")
d.Shift(1).String() // "1234.5"
d.Shift(-1).String() // "12.345"
func (Decimal) Sign ¶
Sign return
0 if d == Null or d == Zero or d == ~0 1 if d > 0 or d == ~+0 -1 if d < 0 or d == ~-0 undefined (1 or -1) if d is NaN
func (Decimal) Sqrt ¶
Sqrt computes the (possibly rounded) square root of a decimal.
Special cases are:
Sqrt(+Inf) = +Inf Sqrt(±0) = ±0 Sqrt(x < 0) = NaN Sqrt(NaN) = NaN
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 ¶ added in v0.6.0
StringFixedCash returns a Cash-rounded fixed-point string with 2 digits after the decimal point. See RoundCash for the interval semantics.
Examples:
NewFromFloat(3.43).StringFixedCash(5) // "3.45" NewFromFloat(3.75).StringFixedCash(50) // "4.00"
func (Decimal) Truncate ¶ added in v0.6.0
Truncate truncates digits from the decimal without rounding (towards zero). precision is the number of digits to keep after the decimal point and must be >= 0; for precision < 0 the decimal is returned unchanged.
Example:
d, _ := NewFromString("123.456")
d.Truncate(2).String() // "123.45"
func (*Decimal) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
Accepts the v1 format (header byte + optional uvarint mantissa) and the v2 extension formats for Decimal, Weight and Length (see BINARY_FORMAT.md). When fed a Weight or Length extension stream, the unit is read but discarded and only the scalar value (m × 10^exp) is returned.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface.
func (*Decimal) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.
type Length ¶ added in v0.9.0
type Length int64
Length represents a fixed-point decimal hold as a 64 bits integer including unit among 7 possible. integer value between -9007199254740991 and 9007199254740991 (or LengthMaxInt) can safely be used as Length using 'm' unit, example :
var a Length = 101 // a is a Length of value 101m
Note 0 is unitialized Length and its value for calculation is 0. Note you need to use Length method for calculation, you cannot use + - * / or any other operators unless Length is a real non-zero integer value with 'm' unit. Unitialized Length is useful when using JSON marshaling/unmarshaling.
Length has similar 64 bits representation like Decimal except 4 bits are used to encode length unit. Length mantissa has 53 bits instead of Decimal mantissa of 57 bits.
func NewLength ¶ added in v0.9.0
NewLength returns a new fixed-point decimal length, value * 10 ^ exp using unit.
func NewLengthFromBytes ¶ added in v0.9.0
NewLengthFromBytes returns a new Length from a slice of bytes representation.
If no length unit is given, 'm' is assumed.
func NewLengthFromDecimal ¶ added in v0.9.0
NewLengthFromDecimal converts a Decimal to Length using unit.
func NewLengthFromString ¶ added in v0.9.0
NewLengthFromString returns a new Length from a string representation.
If no length unit is given, 'm' is assumed.
Example:
l, err := NewLengthFromString("-123.45")
l2, err := NewLengthFromString(".0001m")
l3, err := NewLengthFromString("1.47000mm")
l4, err := NewLengthFromString("3.14e15 km")
func (Length) Add ¶ added in v0.9.0
Add returns l1 + l2 using l1 unit.
Example:
l1, err := NewLengthFromString("123.45km")
l2, err := NewLengthFromString("550m")
l3 := l1.Add(l2)
println(l1.Add(l2))
println(l2.Add(l1))
Output:
124km 124000m
func (Length) BytesTo ¶ added in v0.9.0
BytesTo appends the string representation of the decimal to a slice of byte, if the decimal is Null it appends 0.
func (Length) Compare ¶ added in v0.9.0
Compare compares the numbers represented by l1 and l2 without taking into account lost precision and returns:
-1 if l1 < l2 0 if l1 == l2 +1 if l1 > l2
func (Length) Div ¶ added in v0.9.0
Div returns l / d using l unit. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point and loss bit will be set.
func (Length) GreaterThan ¶ added in v0.9.0
GreaterThan returns true when l1 is greater than l2 (l1 > l2).
func (Length) GreaterThanOrEqual ¶ added in v0.9.0
GreaterThanOrEqual returns true when l1 is greater than or equal to l2 (l1 >= l2).
func (Length) IsExact ¶ added in v0.9.0
IsExact return true if a length has its loss bit not set, ie it has not lost its precision during computation or conversion.
func (Length) IsExactlyZero ¶ added in v0.9.0
IsExactlyZero return
true if l == Null or l == Zero false if l == ~0 or l == -~0 or l == +~0 false if l < 0 false if l > 0
func (Length) IsInfinite ¶ added in v0.9.0
IsInfinite return
true if a l == +Inf or l == -Inf false in any other case
func (Length) IsNaN ¶ added in v0.9.0
IsNaN return
true if l is not a number (NaN) false in any other case
func (Length) IsNegative ¶ added in v0.9.0
IsNegative return
true if l < 0 or l == ~-0 false if l == Null or l == Zero or l == ~0 false if l > 0
func (Length) IsNull ¶ added in v0.9.0
IsNull return
true if l == Null false if l == 0 false if l == ~0 or l == -~0 or l == +~0 false if l < 0 false if l > 0
func (Length) IsPositive ¶ added in v0.9.0
IsPositive return
true if l > 0 or l == ~+0 false if l == Null or l == Zero or l == ~0 false if l < 0 or l == ~-0 false if l is NaN
func (Length) IsSet ¶ added in v0.9.0
IsSet return
false if l == Null true if l == 0 true if l == ~0 or l == -~0 or l == +~0 true if l < 0 true if l > 0
func (Length) IsZero ¶ added in v0.9.0
IsZero return
true if l == Null or l == Zero true if l == ~0 or l == -~0 or l == +~0 false if l < 0 false if l > 0
func (Length) LessThanOrEqual ¶ added in v0.9.0
LessThanOrEqual returns true when l1 is less than or equal to l2 (l1 <= l2).
func (Length) MarshalBinary ¶ added in v1.0.1
MarshalBinary implements the encoding.BinaryMarshaler interface.
When the unit is m (the default unit code 0) the encoding is identical to a Decimal of the same scalar value (1-10 bytes). For any other unit the v2 Length extension format is used (see BINARY_FORMAT.md). Magic values (NaN, ±Inf, NearZero variants) always use the v1 magic byte and lose the unit info.
func (Length) MarshalJSON ¶ added in v0.9.0
MarshalJSON implements the json.Marshaler interface.
func (Length) MarshalText ¶ added in v0.9.0
MarshalText implements the encoding.TextMarshaler interface for XML serialization.
func (Length) Sign ¶ added in v0.9.0
Sign return
0 if l == Null or l == Zero or l == ~0 1 if l > 0 or l == ~+0 -1 if l < 0 or l == ~-0 undefined (1 or -1) if l is NaN
func (Length) String ¶ added in v0.9.0
String returns the string representation of the length with the fixed point and unit.
Example:
l, err := NewLength(-12345, -3, "m") println(l.String())
Output:
-12.345m
func (Length) Unit ¶ added in v0.9.0
Unit returns unit string of l.
Example:
l1, err := NewLengthFromString("100cm")
println(l1.Unit())
Output:
cm
func (*Length) UnmarshalBinary ¶ added in v1.0.1
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
Accepts the v1 format (assumed to be in m), the v2 Decimal extension (assumed to be in m), and the v2 Length extension (with explicit unit). A v2 Weight extension is rejected with ErrFormat.
func (*Length) UnmarshalJSON ¶ added in v0.9.0
UnmarshalJSON implements the json.Unmarshaler interface.
func (*Length) UnmarshalText ¶ added in v0.9.0
UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.
type Weight ¶ added in v0.2.0
type Weight int64
Weight represents a fixed-point decimal hold as a 64 bits integer including unit among 14 possible. integer value between -9007199254740991 and 9007199254740991 (or WeightMaxInt) can safely be used as Weight using 'kg' unit, example :
var a Weight = 101 // a is a Weight of value 101Kg
Note 0 is unitialized Weight and its value for calculation is 0. Note you need to use Weight method for calculation, you cannot use + - * / or any other operators unless Weight is a real non-zero integer value with 'kg' unit. Unitialized Weight is useful when using JSON marshaling/unmarshaling.
Weight has similar 64 bits representation like Decimal except 4 bits are used to encode weight unit. Weight mantissa has 53 bits instead of Decimal mantissa of 57 bits.
func NewWeight ¶ added in v0.3.0
NewWeight returns a new fixed-point decimal weight, value * 10 ^ exp using unit.
func NewWeightFromBytes ¶ added in v0.2.0
NewWeightFromBytes returns a new Weight from a slice of bytes representation.
If no weight unit is given, 'kg' is assumed.
func NewWeightFromDecimal ¶ added in v0.3.0
NewWeightFromDecimal converts a Decimal to Weight using unit.
func NewWeightFromString ¶ added in v0.2.0
NewWeightFromString returns a new Weight from a string representation.
If no weight unit is given, 'kg' is assumed.
Example:
w, err := NewFromString("-123.45")
w2, err := NewFromString(".0001g")
w3, err := NewFromString("1.47000mg")
w4, err := NewFromString("3.14e15 t")
func (Weight) Add ¶ added in v0.2.0
Add returns w1 + w2 using w1 unit.
Example:
w1, err := NewWeightFromString("123.45kg")
w2, err := NewWeightFromString("550g")
w3 := w1.Add(w2)
println(w1.Add(w2))
println(w2.Add(w1))
Output:
124kg 124000g
func (Weight) BytesTo ¶ added in v0.5.0
BytesTo appends the string representation of the decimal to a slice of byte, if the decimal is Null it appends 0.
func (Weight) Compare ¶ added in v0.3.0
Compare compares the numbers represented by w1 and w2 without taking into account lost precision and returns:
-1 if w1 < w2 0 if w1 == w2 +1 if w1 > w2
func (Weight) Div ¶ added in v0.5.0
Div returns w / d using w unit. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point and loss bit will be set.
func (Weight) GreaterThan ¶ added in v0.3.0
GreaterThan returns true when w1 is greater than w2 (w1 > w2).
func (Weight) GreaterThanOrEqual ¶ added in v0.3.0
GreaterThanOrEqual returns true when w1 is greater than or equal to w2 (w1 >= w2).
func (Weight) IsExact ¶ added in v0.3.0
IsExact return true if a weight has its loss bit not set, ie it has not lost its precision during computation or conversion.
func (Weight) IsExactlyZero ¶ added in v0.3.0
IsExactlyZero return
true if w == Null or w == Zero false if w == ~0 or w == -~0 or w == +~0 false if w < 0 false if w > 0
func (Weight) IsInfinite ¶ added in v0.3.0
IsInfinite return
true if a w == +Inf or w == -Inf false in any other case
func (Weight) IsNaN ¶ added in v0.3.0
IsNaN return
true if w is not a a number (NaN) false in any other case
func (Weight) IsNegative ¶ added in v0.3.0
IsNegative return
true if w < 0 or w == ~-0 false if w == Null or w == Zero or w == ~0 false if w > 0
func (Weight) IsNull ¶ added in v0.3.0
IsNull return
true if w == Null false if w == 0 false if w == ~0 or w == -~0 or w == +~0 false if w < 0 false if w > 0
func (Weight) IsPositive ¶ added in v0.3.0
IsPositive return
true if w > 0 or w == ~+0 false if w == Null or w == Zero or w == ~0 false if w < 0 or w == ~-0 false if w is NaN
func (Weight) IsSet ¶ added in v0.3.0
IsSet return
false if w == Null true if w == 0 true if w == ~0 or w == -~0 or w == +~0 true if w < 0 true if w > 0
func (Weight) IsZero ¶ added in v0.3.0
IsZero return
true if w == Null or w == Zero true if w == ~0 or w == -~0 or w == +~0 false if w < 0 false if w > 0
func (Weight) LessThanOrEqual ¶ added in v0.3.0
LessThanOrEqual returns true when w1 is less than or equal to w2 (w1 <= w2).
func (Weight) MarshalBinary ¶ added in v1.0.1
MarshalBinary implements the encoding.BinaryMarshaler interface.
When the unit is kg (the default unit code 0) the encoding is identical to a Decimal of the same scalar value (1-10 bytes), so a Weight in kg and a Decimal with the same value share the same byte sequence. For any other unit the v2 Weight extension format is used (see BINARY_FORMAT.md). Magic values (NaN, ±Inf, NearZero variants) always use the v1 magic byte and lose the unit info.
func (Weight) MarshalJSON ¶ added in v0.2.0
MarshalJSON implements the json.Marshaler interface.
func (Weight) MarshalText ¶ added in v0.2.1
MarshalText implements the encoding.TextMarshaler interface for XML serialization.
func (Weight) Sign ¶ added in v0.3.0
Sign return
0 if w == Null or w == Zero or w == ~0 1 if w > 0 or w == ~+0 -1 if w < 0 or w == ~-0 undefined (1 or -1) if w is NaN
func (Weight) String ¶ added in v0.2.0
String returns the string representation of the weight with the fixed point and unit.
Example:
d := NewWeight(-12345, -3, "kg") println(d.String())
Output:
-12.345kg
func (Weight) Unit ¶ added in v0.2.0
Unit returns unit string of w.
Example:
w1, err := NewWeightFromString("100g")
println(w1.Unit())
Output:
g
func (*Weight) UnmarshalBinary ¶ added in v1.0.1
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
Accepts the v1 format (assumed to be in kg), the v2 Decimal extension (assumed to be in kg), and the v2 Weight extension (with explicit unit). A v2 Length extension is rejected with ErrFormat.
func (*Weight) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON implements the json.Unmarshaler interface.
func (*Weight) UnmarshalText ¶ added in v0.2.1
UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.