Documentation
¶
Overview ¶
Package qdecimal provides exact base-10 decimal arithmetic for finance, banking, exchanges, ledgers, and trading systems.
The core Decimal type stores values as coefficient * 10^-scale and preserves visible scale such as 0.00 or 123.4500. Public operations never mutate their receiver and never rely on package-global precision settings.
Operations that can lose information require an explicit scale and RoundingMode, or a Context/MoneyContext that carries that policy. Exact-only methods such as DivExact, AvgExact, RescaleExact, QuantizeExact, QuantizeStepExact, and context *Exact variants return ErrInexact instead of rounding.
The package also includes Fixed64 for bounded-scale int64 hot paths, exchange tick quantization, range checks, and aggregates, Money for currency-safe arithmetic, nullable wrappers for SQL/JSON boundaries, formatter support, versioned binary encodings, raw BSON helpers, fuzz tests, stress tests, and release gates designed for production finance use.
Index ¶
- Constants
- Variables
- func MustMinorScale(scale int32) int32
- func NormalizeCurrency(currency string) (string, error)
- func ValidateMinorScale(scale int32) error
- type BinaryDecodeOptions
- type Context
- func (c Context) Add(a, b Decimal) (Decimal, error)
- func (c Context) AddExact(a, b Decimal) (Decimal, error)
- func (c Context) Avg(values ...Decimal) (Decimal, error)
- func (c Context) AvgExact(values ...Decimal) (Decimal, error)
- func (c Context) Div(a, b Decimal) (Decimal, error)
- func (c Context) DivExact(a, b Decimal) (Decimal, error)
- func (c Context) MarshalJSON() ([]byte, error)
- func (c Context) Mul(a, b Decimal) (Decimal, error)
- func (c Context) MulExact(a, b Decimal) (Decimal, error)
- func (c Context) Quantize(d Decimal) (Decimal, error)
- func (c Context) QuantizeExact(d Decimal) (Decimal, error)
- func (c Context) QuantizeStep(d, step Decimal) (Decimal, error)
- func (c Context) QuantizeStepExact(d, step Decimal) (Decimal, error)
- func (c Context) String() string
- func (c Context) StringFixed(d Decimal) (string, error)
- func (c Context) Sub(a, b Decimal) (Decimal, error)
- func (c Context) SubExact(a, b Decimal) (Decimal, error)
- func (c Context) Sum(values ...Decimal) (Decimal, error)
- func (c Context) SumExact(values ...Decimal) (Decimal, error)
- func (c *Context) UnmarshalJSON(data []byte) error
- type Decimal
- func Avg(values []Decimal, scale int32, mode RoundingMode) (Decimal, error)
- func AvgExact(values []Decimal) (Decimal, error)
- func FromBigFloat(f *big.Float, scale int32, mode RoundingMode) (Decimal, error)
- func FromFloat64(v float64) (Decimal, error)
- func FromRat(r *big.Rat, scale int32, mode RoundingMode) (Decimal, error)
- func Max(values ...Decimal) Decimal
- func Min(values ...Decimal) Decimal
- func MustParse(s string) Decimal
- func New(coef int64, scale int32) (Decimal, error)
- func NewFromBigInt(coef *big.Int, scale int32) (Decimal, error)
- func NewFromFloat(v float64) (Decimal, error)
- func NewFromFloatWithScale(v float64, scale int32, mode RoundingMode) (Decimal, error)
- func NewFromInt(v int64) Decimal
- func NewFromMinorUnits(units int64, scale int32) (Decimal, error)
- func NewFromString(s string) (Decimal, error)
- func NewFromUint64(v uint64) Decimal
- func Parse(s string) (Decimal, error)
- func ParseBytes(text []byte) (Decimal, error)
- func ParseFlexible(s string) (Decimal, error)
- func ParseWithOptions(s string, opts ParseOptions) (Decimal, error)
- func RequireFromString(s string) Decimal
- func Sum(values ...Decimal) Decimal
- func (d Decimal) Abs() Decimal
- func (d Decimal) Add(other Decimal) Decimal
- func (d Decimal) AppendBinary(dst []byte) ([]byte, error)
- func (d Decimal) AppendText(dst []byte) ([]byte, error)
- func (d Decimal) Between(min, max Decimal, inclusive bool) bool
- func (d Decimal) BinarySize() int
- func (d Decimal) Ceil(scale int32) (Decimal, error)
- func (d Decimal) Clamp(min, max Decimal) Decimal
- func (d Decimal) Cmp(other Decimal) int
- func (d Decimal) Coefficient() *big.Int
- func (d Decimal) Div(other Decimal, scale int32, mode RoundingMode) (Decimal, error)
- func (d Decimal) DivExact(other Decimal) (Decimal, error)
- func (d Decimal) Equal(other Decimal) bool
- func (d Decimal) Floor(scale int32) (Decimal, error)
- func (d Decimal) Format(s fmt.State, verb rune)
- func (d *Decimal) GobDecode(data []byte) error
- func (d Decimal) GobEncode() ([]byte, error)
- func (d Decimal) Int64MinorUnits(scale int32, mode RoundingMode) (int64, error)
- func (d Decimal) Int64MinorUnitsExact(scale int32) (int64, error)
- func (d Decimal) IsInteger() bool
- func (d Decimal) IsZero() bool
- func (d Decimal) JSONNumber() json.Number
- func (d Decimal) Key() string
- func (d Decimal) MarshalBSONDocument(field string) ([]byte, error)
- func (d Decimal) MarshalBSONStringValue() ([]byte, error)
- func (d Decimal) MarshalBinary() ([]byte, error)
- func (d Decimal) MarshalExtendedJSON() ([]byte, error)
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) MarshalJSONWithMode(mode JSONMode) ([]byte, error)
- func (d Decimal) MarshalText() ([]byte, error)
- func (d Decimal) MinorUnits(scale int32, mode RoundingMode) (*big.Int, error)
- func (d Decimal) MinorUnitsExact(scale int32) (*big.Int, error)
- func (d Decimal) Mul(other Decimal) Decimal
- func (d Decimal) Neg() Decimal
- func (d Decimal) Normalize() Decimal
- func (d Decimal) Pow(exp Decimal, scale int32, mode RoundingMode) (Decimal, error)
- func (d Decimal) PowInt(exp uint64) (Decimal, error)
- func (d Decimal) Quantize(template Decimal, mode RoundingMode) (Decimal, error)
- func (d Decimal) QuantizeExact(template Decimal) (Decimal, error)
- func (d Decimal) QuantizeStep(step Decimal, mode RoundingMode) (Decimal, error)
- func (d Decimal) QuantizeStepExact(step Decimal) (Decimal, error)
- func (d Decimal) Rat() *big.Rat
- func (d Decimal) Rescale(scale int32, mode RoundingMode) (Decimal, error)
- func (d Decimal) RescaleExact(scale int32) (Decimal, error)
- func (d Decimal) Round(scale int32, mode RoundingMode) (Decimal, error)
- func (d Decimal) Scale() int32
- func (d *Decimal) Scan(src any) error
- func (d Decimal) Sign() int
- func (d Decimal) String() string
- func (d Decimal) StringFixed(scale int32, mode RoundingMode) (string, error)
- func (d Decimal) Sub(other Decimal) Decimal
- func (d Decimal) Truncate(scale int32) (Decimal, error)
- func (d *Decimal) UnmarshalBSONDocument(data []byte, field string) error
- func (d *Decimal) UnmarshalBSONStringValue(data []byte) error
- func (d *Decimal) UnmarshalBinary(data []byte) error
- func (d *Decimal) UnmarshalBinaryWithOptions(data []byte, opts BinaryDecodeOptions) error
- func (d *Decimal) UnmarshalJSON(data []byte) error
- func (d *Decimal) UnmarshalText(text []byte) error
- func (d Decimal) Value() (driver.Value, error)
- type ExtendedJSON
- type Fixed64
- func AvgFixed64(values []Fixed64, scale int32, mode RoundingMode) (Fixed64, error)
- func AvgFixed64Exact(values []Fixed64, scale int32) (Fixed64, error)
- func Fixed64FromDecimal(d Decimal, scale int32, mode RoundingMode) (Fixed64, error)
- func MaxFixed64(values ...Fixed64) Fixed64
- func MinFixed64(values ...Fixed64) Fixed64
- func NewFixed64(units int64, scale int32) (Fixed64, error)
- func ParseFixed64(s string, scale int32, mode RoundingMode) (Fixed64, error)
- func SumFixed64(values ...Fixed64) (Fixed64, error)
- func (f Fixed64) Abs() (Fixed64, error)
- func (f Fixed64) Add(other Fixed64) (Fixed64, error)
- func (f Fixed64) AppendBinary(dst []byte) ([]byte, error)
- func (f Fixed64) AppendText(dst []byte) ([]byte, error)
- func (f Fixed64) Between(min, max Fixed64, inclusive bool) bool
- func (f Fixed64) BinarySize() int
- func (f Fixed64) Ceil(scale int32) (Fixed64, error)
- func (f Fixed64) Clamp(min, max Fixed64) Fixed64
- func (f Fixed64) Cmp(other Fixed64) int
- func (f Fixed64) Decimal() Decimal
- func (f Fixed64) Div(other Fixed64, scale int32, mode RoundingMode) (Fixed64, error)
- func (f Fixed64) Equal(other Fixed64) bool
- func (f Fixed64) Floor(scale int32) (Fixed64, error)
- func (f Fixed64) Format(s fmt.State, verb rune)
- func (f *Fixed64) GobDecode(data []byte) error
- func (f Fixed64) GobEncode() ([]byte, error)
- func (f Fixed64) IsZero() bool
- func (f Fixed64) Key() string
- func (f Fixed64) MarshalBinary() ([]byte, error)
- func (f Fixed64) MarshalJSON() ([]byte, error)
- func (f Fixed64) MarshalText() ([]byte, error)
- func (f Fixed64) Mul(other Fixed64, scale int32, mode RoundingMode) (Fixed64, error)
- func (f Fixed64) Neg() (Fixed64, error)
- func (f Fixed64) QuantizeStep(step Fixed64, mode RoundingMode) (Fixed64, error)
- func (f Fixed64) Rescale(scale int32, mode RoundingMode) (Fixed64, error)
- func (f Fixed64) Round(scale int32, mode RoundingMode) (Fixed64, error)
- func (f Fixed64) Scale() int32
- func (f *Fixed64) Scan(src any) error
- func (f Fixed64) Sign() int
- func (f Fixed64) String() string
- func (f Fixed64) Sub(other Fixed64) (Fixed64, error)
- func (f Fixed64) Truncate(scale int32) (Fixed64, error)
- func (f Fixed64) Units() int64
- func (f *Fixed64) UnmarshalBinary(data []byte) error
- func (f *Fixed64) UnmarshalJSON(data []byte) error
- func (f *Fixed64) UnmarshalText(text []byte) error
- func (f Fixed64) Value() (driver.Value, error)
- type JSONMode
- type Money
- func AvgMoney(values []Money, scale int32, mode RoundingMode) (Money, error)
- func AvgMoneyExact(values []Money) (Money, error)
- func MaxMoney(values ...Money) (Money, error)
- func MinMoney(values ...Money) (Money, error)
- func MustParseMoney(text string) Money
- func NewMoney(amount Decimal, currency string) (Money, error)
- func NewMoneyFromMinorUnits(units int64, scale int32, currency string) (Money, error)
- func ParseMoney(text string) (Money, error)
- func SumMoney(values ...Money) (Money, error)
- func (m Money) Abs() Money
- func (m Money) Add(other Money) (Money, error)
- func (m Money) Allocate(parts int, scale int32, mode RoundingMode) ([]Money, error)
- func (m Money) AllocateRatios(ratios []int64, scale int32, mode RoundingMode) ([]Money, error)
- func (m Money) Amount() Decimal
- func (m Money) AppendBinary(dst []byte) ([]byte, error)
- func (m Money) AppendText(dst []byte) ([]byte, error)
- func (m Money) Between(min, max Money, inclusive bool) (bool, error)
- func (m Money) BinarySize() int
- func (m Money) Clamp(min, max Money) (Money, error)
- func (m Money) Cmp(other Money) (int, error)
- func (m Money) Currency() string
- func (m Money) Div(divisor Decimal, scale int32, mode RoundingMode) (Money, error)
- func (m Money) Equal(other Money) bool
- func (m Money) Format(s fmt.State, verb rune)
- func (m *Money) GobDecode(data []byte) error
- func (m Money) GobEncode() ([]byte, error)
- func (m Money) Int64MinorUnits(scale int32, mode RoundingMode) (int64, error)
- func (m Money) Int64MinorUnitsExact(scale int32) (int64, error)
- func (m Money) IsZero() bool
- func (m Money) Key() string
- func (m Money) MarshalBinary() ([]byte, error)
- func (m Money) MarshalJSON() ([]byte, error)
- func (m Money) MarshalText() ([]byte, error)
- func (m Money) MinorUnits(scale int32, mode RoundingMode) (*big.Int, error)
- func (m Money) MinorUnitsExact(scale int32) (*big.Int, error)
- func (m Money) Mul(factor Decimal, scale int32, mode RoundingMode) (Money, error)
- func (m Money) Neg() Money
- func (m Money) QuantizeStep(step Decimal, mode RoundingMode) (Money, error)
- func (m Money) QuantizeStepExact(step Decimal) (Money, error)
- func (m Money) Round(scale int32, mode RoundingMode) (Money, error)
- func (m Money) RoundExact(scale int32) (Money, error)
- func (m *Money) Scan(src any) error
- func (m Money) Sign() int
- func (m Money) String() string
- func (m Money) Sub(other Money) (Money, error)
- func (m *Money) UnmarshalBinary(data []byte) error
- func (m *Money) UnmarshalBinaryWithOptions(data []byte, opts BinaryDecodeOptions) error
- func (m *Money) UnmarshalJSON(data []byte) error
- func (m *Money) UnmarshalText(text []byte) error
- func (m Money) Value() (driver.Value, error)
- type MoneyContext
- func (c MoneyContext) Add(a, b Money) (Money, error)
- func (c MoneyContext) AddExact(a, b Money) (Money, error)
- func (c MoneyContext) Allocate(m Money, parts int) ([]Money, error)
- func (c MoneyContext) AllocateRatios(m Money, ratios []int64) ([]Money, error)
- func (c MoneyContext) Avg(values ...Money) (Money, error)
- func (c MoneyContext) AvgExact(values ...Money) (Money, error)
- func (c MoneyContext) Between(m, min, max Money, inclusive bool) (bool, error)
- func (c MoneyContext) Clamp(m, min, max Money) (Money, error)
- func (c MoneyContext) DecimalContext() Context
- func (c MoneyContext) Div(m Money, divisor Decimal) (Money, error)
- func (c MoneyContext) DivExact(m Money, divisor Decimal) (Money, error)
- func (c MoneyContext) FromMinorUnits(units int64) (Money, error)
- func (c MoneyContext) Int64MinorUnits(m Money) (int64, error)
- func (c MoneyContext) Int64MinorUnitsExact(m Money) (int64, error)
- func (c MoneyContext) MarshalJSON() ([]byte, error)
- func (c MoneyContext) Max(values ...Money) (Money, error)
- func (c MoneyContext) Min(values ...Money) (Money, error)
- func (c MoneyContext) Money(amount Decimal) (Money, error)
- func (c MoneyContext) MoneyExact(amount Decimal) (Money, error)
- func (c MoneyContext) Mul(m Money, factor Decimal) (Money, error)
- func (c MoneyContext) MulExact(m Money, factor Decimal) (Money, error)
- func (c MoneyContext) Parse(text string) (Money, error)
- func (c MoneyContext) ParseFlexible(text string) (Money, error)
- func (c MoneyContext) Quantize(m Money) (Money, error)
- func (c MoneyContext) QuantizeExact(m Money) (Money, error)
- func (c MoneyContext) QuantizeStep(m Money, step Decimal) (Money, error)
- func (c MoneyContext) QuantizeStepExact(m Money, step Decimal) (Money, error)
- func (c MoneyContext) String() string
- func (c MoneyContext) Sub(a, b Money) (Money, error)
- func (c MoneyContext) SubExact(a, b Money) (Money, error)
- func (c MoneyContext) Sum(values ...Money) (Money, error)
- func (c MoneyContext) SumExact(values ...Money) (Money, error)
- func (c *MoneyContext) UnmarshalJSON(data []byte) error
- func (c MoneyContext) WithRounding(rounding RoundingMode) (MoneyContext, error)
- func (c MoneyContext) WithScale(scale int32) (MoneyContext, error)
- type NullDecimal
- func (n NullDecimal) AppendText(dst []byte) ([]byte, error)
- func (n NullDecimal) Format(s fmt.State, verb rune)
- func (n NullDecimal) IsZero() bool
- func (n NullDecimal) MarshalJSON() ([]byte, error)
- func (n NullDecimal) MarshalText() ([]byte, error)
- func (n *NullDecimal) Scan(src any) error
- func (n NullDecimal) String() string
- func (n *NullDecimal) UnmarshalJSON(data []byte) error
- func (n *NullDecimal) UnmarshalText(text []byte) error
- func (n NullDecimal) Value() (driver.Value, error)
- type NullFixed64
- func (n NullFixed64) AppendText(dst []byte) ([]byte, error)
- func (n NullFixed64) Format(s fmt.State, verb rune)
- func (n NullFixed64) IsZero() bool
- func (n NullFixed64) MarshalJSON() ([]byte, error)
- func (n NullFixed64) MarshalText() ([]byte, error)
- func (n *NullFixed64) Scan(src any) error
- func (n NullFixed64) String() string
- func (n *NullFixed64) UnmarshalJSON(data []byte) error
- func (n *NullFixed64) UnmarshalText(text []byte) error
- func (n NullFixed64) Value() (driver.Value, error)
- type NullMoney
- func (n NullMoney) AppendText(dst []byte) ([]byte, error)
- func (n NullMoney) Format(s fmt.State, verb rune)
- func (n NullMoney) IsZero() bool
- func (n NullMoney) MarshalJSON() ([]byte, error)
- func (n NullMoney) MarshalText() ([]byte, error)
- func (n *NullMoney) Scan(src any) error
- func (n NullMoney) String() string
- func (n *NullMoney) UnmarshalJSON(data []byte) error
- func (n *NullMoney) UnmarshalText(text []byte) error
- func (n NullMoney) Value() (driver.Value, error)
- type Number
- type ParseOptions
- type RoundingMode
Examples ¶
Constants ¶
const ( DefaultMaxParseDigits = 4096 DefaultMaxParseScale = 4096 DefaultMaxParseExponentDigits = 10 )
const ( RoundBankers = ToNearestEven RoundHalfUp = ToNearestAway RoundHalfDown = ToNearestTowardZero RoundUp = AwayFromZero RoundDown = TowardZero RoundCeil = TowardPositive RoundFloor = TowardNegative )
Common finance-oriented aliases.
const DefaultMaxBSONDecimalTextBytes = DefaultMaxParseDigits + DefaultMaxParseExponentDigits + 16
DefaultMaxBSONDecimalTextBytes bounds untrusted BSON decimal text before it is copied into a Go string and parsed.
const ( // DefaultMaxBinaryCoefficientBytes bounds untrusted binary decimal payloads. // Trusted storage can opt out with BinaryDecodeOptions. DefaultMaxBinaryCoefficientBytes = 4096 )
const DefaultMaxFormatScale int32 = DefaultMaxParseScale
DefaultMaxFormatScale caps precision-driven fmt rescaling for untrusted format strings. Call explicit Rescale/StringFixed APIs when a larger trusted scale is truly required.
Variables ¶
var ( Zero = NewFromInt(0) One = NewFromInt(1) Ten = NewFromInt(10) )
var ( // ErrInvalidSyntax indicates malformed decimal text. ErrInvalidSyntax = errors.New("qdecimal: invalid decimal syntax") // ErrInvalidScale indicates a negative or unsupported decimal scale. ErrInvalidScale = errors.New("qdecimal: invalid decimal scale") // ErrDivisionByZero indicates division by zero. ErrDivisionByZero = errors.New("qdecimal: division by zero") // ErrNonFiniteFloat indicates NaN or infinity was passed to a float constructor. ErrNonFiniteFloat = errors.New("qdecimal: non-finite float") // ErrNilValue indicates SQL NULL or JSON null was assigned to a non-nullable Decimal. ErrNilValue = errors.New("qdecimal: nil cannot be assigned to a non-null decimal") // ErrInvalidSource indicates an unsupported database scanner source type. ErrInvalidSource = errors.New("qdecimal: unsupported database source type") // ErrInvalidRoundingMode indicates an unknown rounding mode. ErrInvalidRoundingMode = errors.New("qdecimal: invalid rounding mode") // ErrOverflow indicates a requested conversion cannot fit in the target type. ErrOverflow = errors.New("qdecimal: overflow") // ErrInexact indicates an exact-only operation would require rounding. ErrInexact = errors.New("qdecimal: inexact decimal result") // ErrEmptyInput indicates an aggregate operation received no values. ErrEmptyInput = errors.New("qdecimal: empty input") // ErrInvalidCurrency indicates a malformed money currency code. ErrInvalidCurrency = errors.New("qdecimal: invalid currency code") // ErrCurrencyMismatch indicates money values with different currencies were combined. ErrCurrencyMismatch = errors.New("qdecimal: currency mismatch") // ErrInvalidAllocation indicates a money allocation with invalid parts or ratios. ErrInvalidAllocation = errors.New("qdecimal: invalid money allocation") // ErrLimitExceeded indicates input exceeded a configured parser resource limit. ErrLimitExceeded = errors.New("qdecimal: input exceeds configured limit") )
var DefaultParseOptions = ParseOptions{ AllowUnicodeMinus: true, AllowPlus: true, DecimalSeparator: '.', MaxDigits: DefaultMaxParseDigits, MaxScale: DefaultMaxParseScale, MaxExponentDigits: DefaultMaxParseExponentDigits, }
DefaultParseOptions accepts canonical ASCII decimals plus the Unicode minus sign.
Functions ¶
func MustMinorScale ¶
MustMinorScale validates common currency minor-unit scales for package initialization and tests.
func NormalizeCurrency ¶
NormalizeCurrency returns an uppercase currency/asset code.
Codes must be 3 to 12 ASCII letters or digits. This covers fiat codes such as USD and IDR, plus common exchange asset codes such as BTC, ETH, USDT, and USDC.
func ValidateMinorScale ¶
ValidateMinorScale validates common currency minor-unit scales.
Types ¶
type BinaryDecodeOptions ¶
BinaryDecodeOptions controls resource limits while decoding versioned binary Decimal and Money payloads. A zero limit disables that specific limit.
func DefaultBinaryDecodeOptions ¶
func DefaultBinaryDecodeOptions() BinaryDecodeOptions
DefaultBinaryDecodeOptions returns the limits used by UnmarshalBinary and GobDecode.
type Context ¶
type Context struct {
Scale int32
Rounding RoundingMode
}
Context is an explicit finance arithmetic policy.
It deliberately replaces package-global precision knobs: callers pass the policy they want at each boundary where rounding may occur.
Example ¶
package main
import (
"fmt"
"log"
"github.com/MeViksry/qdecimal"
)
func main() {
usdCents := qdecimal.MustContext(2, qdecimal.ToNearestEven)
fee, err := usdCents.Mul(
qdecimal.MustParse("123.4567"),
qdecimal.MustParse("0.0025"),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(fee)
}
Output: 0.31
func MustContext ¶
func MustContext(scale int32, rounding RoundingMode) Context
MustContext is for package initialization and tests.
func NewContext ¶
func NewContext(scale int32, rounding RoundingMode) (Context, error)
NewContext validates and returns a finance arithmetic context.
func (Context) AddExact ¶
AddExact returns a + b at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (Context) AvgExact ¶
AvgExact returns the exact average at the context scale, failing with ErrInexact if the average repeats or does not fit the context scale.
func (Context) MarshalJSON ¶
MarshalJSON emits a stable policy object for configuration and audit logs.
func (Context) MulExact ¶
MulExact returns a * b at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (Context) QuantizeExact ¶
QuantizeExact changes d to the context scale without discarding non-zero digits.
func (Context) QuantizeStep ¶
QuantizeStep rounds d to a valid increment, then to the context scale.
func (Context) QuantizeStepExact ¶
QuantizeStepExact changes d to the context scale only when d is already an exact multiple of step and no non-zero digits would be discarded.
func (Context) StringFixed ¶
StringFixed returns d rendered at the context scale.
func (Context) SubExact ¶
SubExact returns a - b at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (Context) SumExact ¶
SumExact returns the exact sum at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (*Context) UnmarshalJSON ¶
UnmarshalJSON decodes and validates a policy object.
type Decimal ¶
type Decimal struct {
// contains filtered or unexported fields
}
Decimal represents coef * 10^-scale.
Decimal has no NaN or infinity state. Non-finite values are rejected at input boundaries so finance code cannot silently propagate invalid amounts.
Example ¶
package main
import (
"fmt"
"log"
"github.com/MeViksry/qdecimal"
)
func main() {
price := qdecimal.MustParse("123.4500")
size := qdecimal.MustParse("0.25")
notional := price.Mul(size)
rounded, err := notional.Round(2, qdecimal.ToNearestEven)
if err != nil {
log.Fatal(err)
}
fmt.Println(rounded)
}
Output: 30.86
func Avg ¶
func Avg(values []Decimal, scale int32, mode RoundingMode) (Decimal, error)
Avg returns the average of values rounded to scale using mode.
func AvgExact ¶
AvgExact returns the exact finite average of values. If the quotient repeats, ErrInexact is returned instead of rounding.
func FromBigFloat ¶
FromBigFloat rounds f to scale using mode.
func FromFloat64 ¶
FromFloat64 converts a finite float through Go's shortest round-trip decimal representation. Prefer Parse or integer minor-unit constructors in finance code; this method is explicit because binary floats are not decimal inputs.
func MustParse ¶
MustParse is for tests and package-level initialization. It panics only when explicitly requested by the caller.
func NewFromBigInt ¶
NewFromBigInt creates a Decimal from a coefficient copy and non-negative scale.
func NewFromFloat ¶
NewFromFloat is a compatibility alias for FromFloat64.
It returns ErrNonFiniteFloat for NaN and infinity instead of panicking.
func NewFromFloatWithScale ¶
func NewFromFloatWithScale(v float64, scale int32, mode RoundingMode) (Decimal, error)
NewFromFloatWithScale converts a finite float and immediately rounds it to scale using mode.
This keeps float boundaries explicit: binary floats are accepted only at an integration edge, and any decimal rounding policy is supplied by the caller.
func NewFromMinorUnits ¶
NewFromMinorUnits creates a Decimal from integer minor units.
Example: NewFromMinorUnits(12345, 2) represents 123.45.
func NewFromString ¶
NewFromString is a compatibility alias for Parse.
func NewFromUint64 ¶
NewFromUint64 creates an integer Decimal from an unsigned value.
func ParseBytes ¶
ParseBytes parses a decimal byte slice using DefaultParseOptions.
func ParseFlexible ¶
ParseFlexible parses common human-entry input: surrounding whitespace, Unicode minus, plus sign, and comma thousands separators.
func ParseWithOptions ¶
func ParseWithOptions(s string, opts ParseOptions) (Decimal, error)
ParseWithOptions parses a decimal string with explicit syntax options.
func RequireFromString ¶
RequireFromString is an alias for MustParse.
func (Decimal) AppendBinary ¶
AppendBinary appends d's stable binary representation to dst.
func (Decimal) AppendText ¶
AppendText appends d's text representation to dst.
func (Decimal) Between ¶
Between reports whether d is inside [min, max] when inclusive is true, or inside (min, max) when inclusive is false. Reversed bounds are accepted.
func (Decimal) BinarySize ¶
BinarySize returns the exact number of bytes produced by MarshalBinary.
func (Decimal) Coefficient ¶
Coefficient returns a defensive copy of d's unscaled integer coefficient.
func (Decimal) DivExact ¶
DivExact divides d by other and returns an exact finite decimal. If the quotient has a repeating decimal expansion, ErrInexact is returned instead of rounding.
func (Decimal) Int64MinorUnits ¶
func (d Decimal) Int64MinorUnits(scale int32, mode RoundingMode) (int64, error)
Int64MinorUnits is like MinorUnits but fails if the result does not fit int64.
func (Decimal) Int64MinorUnitsExact ¶
Int64MinorUnitsExact is like MinorUnitsExact but fails if the result does not fit int64.
func (Decimal) JSONNumber ¶
JSONNumber returns a json.Number for systems that explicitly require numeric JSON tokens and can preserve arbitrary precision.
func (Decimal) MarshalBSONDocument ¶
MarshalBSONDocument returns a minimal BSON document with one string field.
This is a driver-neutral boundary for document databases and message stores that accept raw BSON. It intentionally stores the decimal as precision-safe text rather than lossy floating-point data.
func (Decimal) MarshalBSONStringValue ¶
MarshalBSONStringValue returns the raw BSON string value bytes for d.
The bytes are the BSON value payload only:
int32 byte-length including NUL | UTF-8 decimal text | NUL
qdecimal uses string values for this dependency-free BSON bridge so arbitrary precision and preserved scale are not limited by Decimal128's finite range.
func (Decimal) MarshalBinary ¶
MarshalBinary implements encoding.BinaryMarshaler using a stable versioned network-order format:
QDEC | version | scale uint32 | coefficient length uint32 | coefficient bytes
The coefficient is stored as signed magnitude: one sign byte plus big-endian absolute coefficient bytes.
func (Decimal) MarshalExtendedJSON ¶
MarshalExtendedJSON emits MongoDB-style Decimal128 Extended JSON.
func (Decimal) MarshalJSON ¶
MarshalJSON emits a JSON string. This avoids lossy float interpretation in JavaScript, database gateways, and message buses.
Example ¶
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/MeViksry/qdecimal"
)
func main() {
data, err := json.Marshal(qdecimal.MustParse("123.4500"))
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
}
Output: "123.4500"
func (Decimal) MarshalJSONWithMode ¶
MarshalJSONWithMode emits d using an explicit JSON policy.
func (Decimal) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (Decimal) MinorUnits ¶
MinorUnits returns d rounded to scale and represented as an integer number of minor units.
func (Decimal) MinorUnitsExact ¶
MinorUnitsExact returns d as minor units only when no non-zero digit would be discarded at scale.
func (Decimal) Pow ¶
Pow returns d^exp rounded to scale using mode.
exp must be an integer-valued Decimal. Fractional exponents are rejected with ErrInexact instead of using a hidden floating-point approximation. Use PowInt when a non-negative integer exponent should preserve the exact natural scale.
func (Decimal) Quantize ¶
func (d Decimal) Quantize(template Decimal, mode RoundingMode) (Decimal, error)
Quantize rounds d to the same scale as template.
func (Decimal) QuantizeExact ¶
QuantizeExact changes d to template's scale only when no non-zero digit would be lost.
func (Decimal) QuantizeStep ¶
func (d Decimal) QuantizeStep(step Decimal, mode RoundingMode) (Decimal, error)
QuantizeStep rounds d to the nearest multiple of step using mode.
This is intended for exchange tick sizes and banking increments that are not expressible by scale alone, such as 0.05.
func (Decimal) QuantizeStepExact ¶
QuantizeStepExact changes d to step's scale only when d is already an exact multiple of step. ErrInexact is returned instead of rounding.
func (Decimal) Rescale ¶
func (d Decimal) Rescale(scale int32, mode RoundingMode) (Decimal, error)
Rescale changes d to scale using mode when digits must be discarded.
func (Decimal) RescaleExact ¶
RescaleExact changes d to scale only when no non-zero digit would be lost.
If reducing scale would require rounding, ErrInexact is returned.
func (Decimal) Round ¶
func (d Decimal) Round(scale int32, mode RoundingMode) (Decimal, error)
Round is an alias for Rescale.
func (Decimal) String ¶
String returns the decimal string while preserving scale, including values like 0.00.
func (Decimal) StringFixed ¶
func (d Decimal) StringFixed(scale int32, mode RoundingMode) (string, error)
StringFixed rounds d to scale and returns the fixed-scale representation.
func (*Decimal) UnmarshalBSONDocument ¶
UnmarshalBSONDocument decodes a minimal single-field BSON document into d.
func (*Decimal) UnmarshalBSONStringValue ¶
UnmarshalBSONStringValue decodes a raw BSON string value payload into d.
func (*Decimal) UnmarshalBinary ¶
UnmarshalBinary implements encoding.BinaryUnmarshaler using DefaultBinaryDecodeOptions().
func (*Decimal) UnmarshalBinaryWithOptions ¶
func (d *Decimal) UnmarshalBinaryWithOptions(data []byte, opts BinaryDecodeOptions) error
UnmarshalBinaryWithOptions decodes d's stable binary representation with explicit resource limits for trusted or untrusted storage boundaries.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON accepts either a JSON string or a JSON number.
func (*Decimal) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type ExtendedJSON ¶
type ExtendedJSON struct {
Decimal Decimal
}
ExtendedJSON wraps Decimal using MongoDB-style Decimal128 Extended JSON:
{"$numberDecimal":"123.45"}
It intentionally avoids importing a database driver. Driver-specific BSON adapters can build on this stable representation.
func AsExtendedJSON ¶
func AsExtendedJSON(d Decimal) ExtendedJSON
AsExtendedJSON returns a MongoDB-style Extended JSON wrapper for d.
func (ExtendedJSON) IsZero ¶
func (e ExtendedJSON) IsZero() bool
IsZero reports whether the wrapped decimal is numerically zero.
func (ExtendedJSON) MarshalJSON ¶
func (e ExtendedJSON) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
func (*ExtendedJSON) UnmarshalJSON ¶
func (e *ExtendedJSON) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
type Fixed64 ¶
type Fixed64 struct {
// contains filtered or unexported fields
}
Fixed64 is a compact fixed-scale decimal for hot ledger and trading paths.
It stores integer minor units and a non-negative scale. Use Decimal for arbitrary precision; use Fixed64 when the business domain has a known bounded scale and int64 range is sufficient.
Example ¶
package main
import (
"fmt"
"log"
"github.com/MeViksry/qdecimal"
)
func main() {
price, err := qdecimal.ParseFixed64("123.456", 2, qdecimal.ToNearestAway)
if err != nil {
log.Fatal(err)
}
rate, err := qdecimal.NewFixed64(25, 4)
if err != nil {
log.Fatal(err)
}
fee, err := price.Mul(rate, 4, qdecimal.ToNearestEven)
if err != nil {
log.Fatal(err)
}
fmt.Println(fee)
}
Output: 0.3086
func AvgFixed64 ¶
func AvgFixed64(values []Fixed64, scale int32, mode RoundingMode) (Fixed64, error)
AvgFixed64 returns the average of values rounded to scale using mode.
func AvgFixed64Exact ¶
AvgFixed64Exact returns the exact finite average of values at scale. If the quotient repeats or does not fit scale, ErrInexact is returned.
func Fixed64FromDecimal ¶
func Fixed64FromDecimal(d Decimal, scale int32, mode RoundingMode) (Fixed64, error)
Fixed64FromDecimal converts d to Fixed64 at scale using mode.
func MaxFixed64 ¶
MaxFixed64 returns the largest value. An empty input returns the zero value.
func MinFixed64 ¶
MinFixed64 returns the smallest value. An empty input returns the zero value.
func NewFixed64 ¶
NewFixed64 creates a fixed-scale decimal from integer units.
func ParseFixed64 ¶
func ParseFixed64(s string, scale int32, mode RoundingMode) (Fixed64, error)
ParseFixed64 parses input and rounds it to scale.
func SumFixed64 ¶
SumFixed64 returns the exact sum of values. The fast path keeps same-scale sums in int64 units; mixed-scale or overflowing sums fall back to Decimal and still return ErrOverflow if the final exact result cannot fit in Fixed64.
func (Fixed64) AppendBinary ¶
AppendBinary appends f's stable binary representation to dst.
func (Fixed64) AppendText ¶
AppendText appends f's text representation to dst.
func (Fixed64) Between ¶
Between reports whether f is inside [min, max] when inclusive is true, or inside (min, max) when inclusive is false. Reversed bounds are accepted.
func (Fixed64) BinarySize ¶
BinarySize returns the exact number of bytes produced by MarshalBinary.
func (Fixed64) MarshalBinary ¶
MarshalBinary implements encoding.BinaryMarshaler using a stable versioned network-order fixed64 format:
QF64 | version | scale uint32 | units int64
func (Fixed64) MarshalJSON ¶
MarshalJSON emits a precision-preserving JSON string.
func (Fixed64) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (Fixed64) QuantizeStep ¶
func (f Fixed64) QuantizeStep(step Fixed64, mode RoundingMode) (Fixed64, error)
QuantizeStep rounds f to a valid multiple of step using mode.
This is intended for bounded-scale exchange ticks, lot sizes, and banking increments. The returned value uses step's scale.
func (Fixed64) Rescale ¶
func (f Fixed64) Rescale(scale int32, mode RoundingMode) (Fixed64, error)
Rescale changes f to scale using mode when minor digits must be discarded.
func (Fixed64) Round ¶
func (f Fixed64) Round(scale int32, mode RoundingMode) (Fixed64, error)
Round is an alias for Rescale.
func (*Fixed64) UnmarshalBinary ¶
UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (*Fixed64) UnmarshalJSON ¶
UnmarshalJSON accepts a JSON string or number.
func (*Fixed64) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler and preserves the parsed scale.
type Money ¶
type Money struct {
// contains filtered or unexported fields
}
Money couples an exact Decimal amount with a normalized currency or asset code.
Money prevents accidental arithmetic across currencies. It does not embed an ISO-4217 table; callers choose scale and rounding policies explicitly so the library does not ship stale monetary metadata.
func AvgMoney ¶
func AvgMoney(values []Money, scale int32, mode RoundingMode) (Money, error)
AvgMoney returns the average of money values rounded to scale using mode. All values must use one currency.
func AvgMoneyExact ¶
AvgMoneyExact returns the exact finite average of money values. If the quotient repeats, ErrInexact is returned instead of rounding.
func MustParseMoney ¶
MustParseMoney is for tests and package-level initialization. It panics only when explicitly requested by the caller.
func NewMoneyFromMinorUnits ¶
NewMoneyFromMinorUnits creates Money from integer minor units and an explicit scale.
func ParseMoney ¶
ParseMoney parses canonical "CODE amount" text.
Example: ParseMoney("USD 123.45").
func SumMoney ¶
SumMoney returns the exact sum of money values. All values must use one currency because summing across currencies is a category error.
func (Money) Allocate ¶
Allocate splits m into parts at scale while preserving the rounded total.
Remainder minor units are distributed from the first part forward. Negative values distribute negative remainders the same way, preserving exact totals.
func (Money) AllocateRatios ¶
AllocateRatios splits m according to non-negative ratios at scale while preserving the rounded total.
func (Money) AppendBinary ¶
AppendBinary appends m's stable binary representation to dst.
func (Money) AppendText ¶
AppendText appends m's canonical "CODE amount" text representation to dst.
func (Money) Between ¶
Between reports whether m is inside [min, max] when inclusive is true, or inside (min, max) when inclusive is false. Reversed bounds are accepted.
func (Money) BinarySize ¶
BinarySize returns the exact number of bytes produced by MarshalBinary.
func (Money) Int64MinorUnits ¶
func (m Money) Int64MinorUnits(scale int32, mode RoundingMode) (int64, error)
Int64MinorUnits is like MinorUnits but fails if the result does not fit int64.
func (Money) Int64MinorUnitsExact ¶
Int64MinorUnitsExact is like MinorUnitsExact but fails if the result does not fit int64.
func (Money) MarshalBinary ¶
MarshalBinary implements encoding.BinaryMarshaler using a stable versioned network-order money format:
QMON | version | currency length uint16 | currency bytes | decimal length uint32 | decimal binary bytes
func (Money) MarshalJSON ¶
MarshalJSON emits {"amount":"...","currency":"..."}.
func (Money) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (Money) MinorUnits ¶
MinorUnits returns m rounded to scale as integer minor units.
func (Money) MinorUnitsExact ¶
MinorUnitsExact returns m as integer minor units only when no non-zero digit would be discarded at scale.
func (Money) QuantizeStep ¶
func (m Money) QuantizeStep(step Decimal, mode RoundingMode) (Money, error)
QuantizeStep rounds m's amount to a valid increment, such as an exchange tick.
func (Money) QuantizeStepExact ¶
QuantizeStepExact changes m's amount to step's scale only when it is already an exact multiple of step.
func (Money) Round ¶
func (m Money) Round(scale int32, mode RoundingMode) (Money, error)
Round rounds m's amount to scale using mode.
func (Money) RoundExact ¶
RoundExact changes m's amount to scale only when no non-zero digit would be lost.
func (*Money) Scan ¶
Scan implements database/sql.Scanner using the canonical "CODE amount" text format.
func (*Money) UnmarshalBinary ¶
UnmarshalBinary implements encoding.BinaryUnmarshaler using DefaultBinaryDecodeOptions() for the embedded Decimal payload.
func (*Money) UnmarshalBinaryWithOptions ¶
func (m *Money) UnmarshalBinaryWithOptions(data []byte, opts BinaryDecodeOptions) error
UnmarshalBinaryWithOptions decodes a Money binary payload with explicit resource limits for the embedded Decimal amount.
func (*Money) UnmarshalJSON ¶
UnmarshalJSON accepts {"amount":"...","currency":"..."}.
func (*Money) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler for "CODE amount" text.
type MoneyContext ¶
type MoneyContext struct {
Currency string
Scale int32
Rounding RoundingMode
}
MoneyContext is an explicit policy for one currency or asset.
It carries currency, scale, and rounding together so services can pass an auditable money policy without package-global precision or currency metadata.
Example ¶
package main
import (
"fmt"
"log"
"github.com/MeViksry/qdecimal"
)
func main() {
usd := qdecimal.MustMoneyContext("usd", 2, qdecimal.ToNearestAway)
amount, err := usd.Parse("10.005")
if err != nil {
log.Fatal(err)
}
rebate, err := usd.Parse("0.005")
if err != nil {
log.Fatal(err)
}
total, err := usd.Add(amount, rebate)
if err != nil {
log.Fatal(err)
}
fmt.Println(total)
}
Output: USD 10.02
func MustMoneyContext ¶
func MustMoneyContext(currency string, scale int32, rounding RoundingMode) MoneyContext
MustMoneyContext is for package initialization and tests.
func NewMoneyContext ¶
func NewMoneyContext(currency string, scale int32, rounding RoundingMode) (MoneyContext, error)
NewMoneyContext validates and returns a money arithmetic context.
func (MoneyContext) Add ¶
func (c MoneyContext) Add(a, b Money) (Money, error)
Add returns a + b rounded to the context scale.
func (MoneyContext) AddExact ¶
func (c MoneyContext) AddExact(a, b Money) (Money, error)
AddExact returns a + b at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (MoneyContext) Allocate ¶
func (c MoneyContext) Allocate(m Money, parts int) ([]Money, error)
Allocate splits money into equal parts at the context scale.
func (MoneyContext) AllocateRatios ¶
func (c MoneyContext) AllocateRatios(m Money, ratios []int64) ([]Money, error)
AllocateRatios splits money by ratios at the context scale.
func (MoneyContext) Avg ¶
func (c MoneyContext) Avg(values ...Money) (Money, error)
Avg returns the average of values rounded to the context scale.
func (MoneyContext) AvgExact ¶
func (c MoneyContext) AvgExact(values ...Money) (Money, error)
AvgExact returns the average at the context scale without rounding.
func (MoneyContext) Between ¶
func (c MoneyContext) Between(m, min, max Money, inclusive bool) (bool, error)
Between reports whether m is inside the range after all values are quantized to the context scale. Reversed bounds are accepted.
func (MoneyContext) Clamp ¶
func (c MoneyContext) Clamp(m, min, max Money) (Money, error)
Clamp constrains m to [min, max] after quantizing all values to the context scale. Reversed bounds are accepted.
func (MoneyContext) DecimalContext ¶
func (c MoneyContext) DecimalContext() Context
DecimalContext returns the numeric scale/rounding policy.
func (MoneyContext) Div ¶
func (c MoneyContext) Div(m Money, divisor Decimal) (Money, error)
Div divides money by divisor and rounds to the context scale.
func (MoneyContext) DivExact ¶
func (c MoneyContext) DivExact(m Money, divisor Decimal) (Money, error)
DivExact divides money by divisor at the context scale without rounding.
func (MoneyContext) FromMinorUnits ¶
func (c MoneyContext) FromMinorUnits(units int64) (Money, error)
FromMinorUnits creates money from integer minor units at the context scale.
func (MoneyContext) Int64MinorUnits ¶
func (c MoneyContext) Int64MinorUnits(m Money) (int64, error)
Int64MinorUnits returns money as int64 minor units at the context scale.
func (MoneyContext) Int64MinorUnitsExact ¶
func (c MoneyContext) Int64MinorUnitsExact(m Money) (int64, error)
Int64MinorUnitsExact returns money as int64 minor units at the context scale only when no non-zero digit would be discarded.
func (MoneyContext) MarshalJSON ¶
func (c MoneyContext) MarshalJSON() ([]byte, error)
MarshalJSON emits a stable policy object for configuration and audit logs.
func (MoneyContext) Max ¶
func (c MoneyContext) Max(values ...Money) (Money, error)
Max returns the largest value after quantizing all inputs to the context scale.
func (MoneyContext) Min ¶
func (c MoneyContext) Min(values ...Money) (Money, error)
Min returns the smallest value after quantizing all inputs to the context scale.
func (MoneyContext) Money ¶
func (c MoneyContext) Money(amount Decimal) (Money, error)
Money rounds amount to the context scale and attaches the context currency.
func (MoneyContext) MoneyExact ¶
func (c MoneyContext) MoneyExact(amount Decimal) (Money, error)
MoneyExact attaches the context currency only when amount already fits the context scale without losing non-zero digits.
func (MoneyContext) Mul ¶
func (c MoneyContext) Mul(m Money, factor Decimal) (Money, error)
Mul multiplies money by factor and rounds to the context scale.
func (MoneyContext) MulExact ¶
func (c MoneyContext) MulExact(m Money, factor Decimal) (Money, error)
MulExact multiplies money by factor at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (MoneyContext) Parse ¶
func (c MoneyContext) Parse(text string) (Money, error)
Parse parses amount text, rounds it to the context scale, and attaches currency.
func (MoneyContext) ParseFlexible ¶
func (c MoneyContext) ParseFlexible(text string) (Money, error)
ParseFlexible parses human-entry text using ParseFlexible, rounds it, and attaches currency.
func (MoneyContext) Quantize ¶
func (c MoneyContext) Quantize(m Money) (Money, error)
Quantize rounds money to the context scale after validating currency.
func (MoneyContext) QuantizeExact ¶
func (c MoneyContext) QuantizeExact(m Money) (Money, error)
QuantizeExact changes money to the context scale without discarding non-zero digits.
func (MoneyContext) QuantizeStep ¶
func (c MoneyContext) QuantizeStep(m Money, step Decimal) (Money, error)
QuantizeStep rounds money to a valid increment, then to the context scale.
func (MoneyContext) QuantizeStepExact ¶
func (c MoneyContext) QuantizeStepExact(m Money, step Decimal) (Money, error)
QuantizeStepExact changes money to the context scale only when it is already an exact multiple of step and no non-zero digits would be discarded.
func (MoneyContext) String ¶
func (c MoneyContext) String() string
func (MoneyContext) Sub ¶
func (c MoneyContext) Sub(a, b Money) (Money, error)
Sub returns a - b rounded to the context scale.
func (MoneyContext) SubExact ¶
func (c MoneyContext) SubExact(a, b Money) (Money, error)
SubExact returns a - b at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (MoneyContext) Sum ¶
func (c MoneyContext) Sum(values ...Money) (Money, error)
Sum returns the exact sum of values rounded to the context scale.
func (MoneyContext) SumExact ¶
func (c MoneyContext) SumExact(values ...Money) (Money, error)
SumExact returns the exact sum of values at the context scale, failing with ErrInexact if non-zero digits would be discarded.
func (*MoneyContext) UnmarshalJSON ¶
func (c *MoneyContext) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes, normalizes, and validates a money policy object.
func (MoneyContext) WithRounding ¶
func (c MoneyContext) WithRounding(rounding RoundingMode) (MoneyContext, error)
WithRounding returns c with a different rounding mode.
func (MoneyContext) WithScale ¶
func (c MoneyContext) WithScale(scale int32) (MoneyContext, error)
WithScale returns c with a different scale.
type NullDecimal ¶
NullDecimal represents a Decimal that may be SQL NULL or JSON null.
func NewNullDecimal ¶
func NewNullDecimal(d Decimal) NullDecimal
NewNullDecimal marks d as valid even when d is zero.
func (NullDecimal) AppendText ¶
func (n NullDecimal) AppendText(dst []byte) ([]byte, error)
AppendText appends n's text representation to dst.
func (NullDecimal) Format ¶
func (n NullDecimal) Format(s fmt.State, verb rune)
Format implements fmt.Formatter.
func (NullDecimal) IsZero ¶
func (n NullDecimal) IsZero() bool
IsZero reports whether n is invalid/null.
func (NullDecimal) MarshalJSON ¶
func (n NullDecimal) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
func (NullDecimal) MarshalText ¶
func (n NullDecimal) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
func (*NullDecimal) Scan ¶
func (n *NullDecimal) Scan(src any) error
Scan implements database/sql.Scanner.
func (NullDecimal) String ¶
func (n NullDecimal) String() string
String returns n's decimal text or "null".
func (*NullDecimal) UnmarshalJSON ¶
func (n *NullDecimal) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
func (*NullDecimal) UnmarshalText ¶
func (n *NullDecimal) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
type NullFixed64 ¶
NullFixed64 represents a Fixed64 that may be SQL NULL or JSON null.
func NewNullFixed64 ¶
func NewNullFixed64(f Fixed64) NullFixed64
NewNullFixed64 marks f as valid even when f is zero.
func (NullFixed64) AppendText ¶
func (n NullFixed64) AppendText(dst []byte) ([]byte, error)
AppendText appends n's text representation to dst.
func (NullFixed64) Format ¶
func (n NullFixed64) Format(s fmt.State, verb rune)
Format implements fmt.Formatter.
func (NullFixed64) IsZero ¶
func (n NullFixed64) IsZero() bool
IsZero reports whether n is invalid/null.
func (NullFixed64) MarshalJSON ¶
func (n NullFixed64) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
func (NullFixed64) MarshalText ¶
func (n NullFixed64) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
func (*NullFixed64) Scan ¶
func (n *NullFixed64) Scan(src any) error
Scan implements database/sql.Scanner.
func (NullFixed64) String ¶
func (n NullFixed64) String() string
String returns n's fixed decimal text or "null".
func (*NullFixed64) UnmarshalJSON ¶
func (n *NullFixed64) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
func (*NullFixed64) UnmarshalText ¶
func (n *NullFixed64) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
type NullMoney ¶
NullMoney represents Money that may be SQL NULL or JSON null.
func (NullMoney) AppendText ¶
AppendText appends n's text representation to dst.
func (NullMoney) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (NullMoney) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*NullMoney) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*NullMoney) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Number ¶
type Number struct {
Decimal Decimal
}
Number wraps Decimal to marshal as a JSON number token instead of the default quoted string. Use it only with systems that preserve arbitrary-precision JSON numbers end to end.
func (Number) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*Number) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type ParseOptions ¶
type ParseOptions struct {
TrimSpace bool
AllowUnicodeMinus bool
AllowPlus bool
AllowThousands bool
DecimalSeparator rune
ThousandsSeparator rune
MaxDigits int
MaxScale int32
MaxExponentDigits int
}
ParseOptions controls accepted human-input syntax. Parse uses strict, locale-neutral defaults except for the Unicode minus sign.
type RoundingMode ¶
type RoundingMode byte
RoundingMode controls how discarded fractional digits are handled.
const ( // ToNearestEven rounds to the nearest value, with ties going to the even digit. ToNearestEven RoundingMode = iota // ToNearestAway rounds to the nearest value, with ties away from zero. ToNearestAway // ToNearestTowardZero rounds to the nearest value, with ties toward zero. ToNearestTowardZero // AwayFromZero rounds any discarded non-zero digit away from zero. AwayFromZero // TowardZero truncates discarded digits. TowardZero // TowardPositive rounds toward +infinity. TowardPositive // TowardNegative rounds toward -infinity. TowardNegative )
func ParseRoundingMode ¶
func ParseRoundingMode(text string) (RoundingMode, error)
ParseRoundingMode parses stable names and common finance aliases.
func (RoundingMode) MarshalJSON ¶
func (m RoundingMode) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler as a stable string.
func (RoundingMode) MarshalText ¶
func (m RoundingMode) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
func (RoundingMode) String ¶
func (m RoundingMode) String() string
String returns a stable audit-friendly name for m.
func (*RoundingMode) UnmarshalJSON ¶
func (m *RoundingMode) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler from a stable string.
func (*RoundingMode) UnmarshalText ¶
func (m *RoundingMode) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler.