Documentation
¶
Overview ¶
Package math implements custom Cosmos SDK math types used for arithmetic operations. Signed and unsigned integer types utilize Golang's standard library big integers types, having a maximum bit length of 256 bits.
Index ¶
- Constants
- Variables
- func FormatDec(v string) (string, error)
- func FormatInt(v string) (string, error)
- func IntEq(t *testing.T, exp, got Int) (*testing.T, bool, string, string, string)
- func LegacyDecApproxEq(t *testing.T, d1, d2, tol LegacyDec) (*testing.T, bool, string, string, string)
- func LegacyDecEq(t *testing.T, exp, got LegacyDec) (*testing.T, bool, string, string, string)
- func LegacyDecsEqual(d1s, d2s []LegacyDec) bool
- func LegacySortableDecBytes(dec LegacyDec) []byte
- func LegacyValidSortableDec(dec LegacyDec) bool
- func Max[T constraints.Ordered](a, b T, rest ...T) T
- func Min[T constraints.Ordered](a, b T, rest ...T) T
- func UintOverflow(i *big.Int) error
- type Dec
- func (x Dec) Add(y Dec) (Dec, error)
- func (x Dec) BigInt() (*big.Int, error)
- func (x Dec) Cmp(y Dec) int
- func (x Dec) Equal(y Dec) bool
- func (x Dec) Int64() (int64, error)
- func (x Dec) IsFinite() bool
- func (x Dec) IsNegative() bool
- func (x Dec) IsPositive() bool
- func (x Dec) IsZero() bool
- func (x Dec) Marshal() ([]byte, error)
- func (x Dec) MarshalJSON() ([]byte, error)
- func (x Dec) MarshalTo(data []byte) (n int, err error)
- func (x Dec) Modulo(y Dec) (Dec, error)
- func (x Dec) Mul(y Dec) (Dec, error)
- func (x Dec) MulExact(y Dec) (Dec, error)
- func (x Dec) NumDecimalPlaces() uint32
- func (x Dec) Quo(y Dec) (Dec, error)
- func (x Dec) QuoExact(y Dec) (Dec, error)
- func (x Dec) QuoInteger(y Dec) (Dec, error)
- func (x Dec) Reduce() (Dec, int)
- func (x Dec) SdkIntTrim() (Int, error)
- func (x Dec) Size() int
- func (x Dec) String() string
- func (x Dec) Sub(y Dec) (Dec, error)
- func (x Dec) Text(format byte) string
- func (x *Dec) Unmarshal(data []byte) error
- func (x *Dec) UnmarshalJSON(data []byte) error
- type Int
- func MaxInt(i, i2 Int) Int
- func MinInt(i1, i2 Int) Int
- func NewInt(n int64) Int
- func NewIntFromBigInt(i *big.Int) Int
- func NewIntFromBigIntMut(i *big.Int) Int
- func NewIntFromString(s string) (res Int, ok bool)
- func NewIntFromUint64(n uint64) Int
- func NewIntWithDecimal(n int64, dec int) Int
- func OneInt() Int
- func ZeroInt() Int
- func (i Int) Abs() Int
- func (i Int) Add(i2 Int) (res Int)
- func (i Int) AddRaw(i2 int64) Int
- func (i Int) BigInt() *big.Int
- func (i Int) BigIntMut() *big.Int
- func (i Int) Equal(i2 Int) bool
- func (i Int) GT(i2 Int) bool
- func (i Int) GTE(i2 Int) bool
- func (i Int) Int64() int64
- func (i Int) IsInt64() bool
- func (i Int) IsNegative() bool
- func (i Int) IsNil() bool
- func (i Int) IsPositive() bool
- func (i Int) IsUint64() bool
- func (i Int) IsZero() bool
- func (i Int) LT(i2 Int) bool
- func (i Int) LTE(i2 Int) bool
- func (i Int) Marshal() ([]byte, error)
- func (i Int) MarshalAmino() ([]byte, error)
- func (i Int) MarshalJSON() ([]byte, error)
- func (i *Int) MarshalTo(data []byte) (n int, err error)
- func (i Int) MarshalYAML() (interface{}, error)
- func (i Int) Mod(i2 Int) Int
- func (i Int) ModRaw(i2 int64) Int
- func (i Int) Mul(i2 Int) (res Int)
- func (i Int) MulRaw(i2 int64) Int
- func (i Int) Neg() (res Int)
- func (i Int) Quo(i2 Int) (res Int)
- func (i Int) QuoRaw(i2 int64) Int
- func (i Int) SafeAdd(i2 Int) (res Int, err error)
- func (i Int) SafeMod(i2 Int) (res Int, err error)
- func (i Int) SafeMul(i2 Int) (res Int, err error)
- func (i Int) SafeQuo(i2 Int) (res Int, err error)
- func (i Int) SafeSub(i2 Int) (res Int, err error)
- func (i Int) Sign() int
- func (i *Int) Size() int
- func (i Int) String() string
- func (i Int) Sub(i2 Int) (res Int)
- func (i Int) SubRaw(i2 int64) Int
- func (i Int) ToLegacyDec() LegacyDec
- func (i Int) Uint64() uint64
- func (i *Int) Unmarshal(data []byte) error
- func (i *Int) UnmarshalAmino(bz []byte) error
- func (i *Int) UnmarshalJSON(bz []byte) error
- type LegacyDec
- func LegacyMaxDec(d1, d2 LegacyDec) LegacyDec
- func LegacyMinDec(d1, d2 LegacyDec) LegacyDec
- func LegacyMustNewDecFromStr(s string) LegacyDec
- func LegacyNewDec(i int64) LegacyDec
- func LegacyNewDecFromBigInt(i *big.Int) LegacyDec
- func LegacyNewDecFromBigIntWithPrec(i *big.Int, prec int64) LegacyDec
- func LegacyNewDecFromInt(i Int) LegacyDec
- func LegacyNewDecFromIntWithPrec(i Int, prec int64) LegacyDec
- func LegacyNewDecFromStr(str string) (LegacyDec, error)
- func LegacyNewDecWithPrec(i, prec int64) LegacyDec
- func LegacyOneDec() LegacyDec
- func LegacySmallestDec() LegacyDec
- func LegacyZeroDec() LegacyDec
- func (d LegacyDec) Abs() LegacyDec
- func (d LegacyDec) AbsMut() LegacyDec
- func (d LegacyDec) Add(d2 LegacyDec) LegacyDec
- func (d LegacyDec) AddMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) ApproxRoot(root uint64) (guess LegacyDec, err error)
- func (d LegacyDec) ApproxSqrt() (LegacyDec, error)
- func (d LegacyDec) BigInt() *big.Int
- func (d LegacyDec) BigIntMut() *big.Int
- func (d LegacyDec) Ceil() LegacyDec
- func (d LegacyDec) Clone() LegacyDec
- func (d LegacyDec) Equal(d2 LegacyDec) bool
- func (d LegacyDec) Float64() (float64, error)
- func (d LegacyDec) Format(s fmt.State, verb rune)
- func (d LegacyDec) GT(d2 LegacyDec) bool
- func (d LegacyDec) GTE(d2 LegacyDec) bool
- func (d LegacyDec) ImmutOp(op func(LegacyDec, LegacyDec) LegacyDec, d2 LegacyDec) LegacyDec
- func (d LegacyDec) ImmutOpInt(op func(LegacyDec, Int) LegacyDec, d2 Int) LegacyDec
- func (d LegacyDec) ImmutOpInt64(op func(LegacyDec, int64) LegacyDec, d2 int64) LegacyDec
- func (d LegacyDec) IsInValidRange() bool
- func (d LegacyDec) IsInteger() bool
- func (d LegacyDec) IsNegative() bool
- func (d LegacyDec) IsNil() bool
- func (d LegacyDec) IsPositive() bool
- func (d LegacyDec) IsZero() bool
- func (d LegacyDec) LT(d2 LegacyDec) bool
- func (d LegacyDec) LTE(d2 LegacyDec) bool
- func (d LegacyDec) Marshal() ([]byte, error)
- func (d LegacyDec) MarshalAmino() ([]byte, error)
- func (d LegacyDec) MarshalJSON() ([]byte, error)
- func (d *LegacyDec) MarshalTo(data []byte) (n int, err error)
- func (d LegacyDec) MarshalYAML() (interface{}, error)
- func (d LegacyDec) Mul(d2 LegacyDec) LegacyDec
- func (d LegacyDec) MulInt(i Int) LegacyDec
- func (d LegacyDec) MulInt64(i int64) LegacyDec
- func (d LegacyDec) MulInt64Mut(i int64) LegacyDec
- func (d LegacyDec) MulIntMut(i Int) LegacyDec
- func (d LegacyDec) MulMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) MulRoundUp(d2 LegacyDec) LegacyDec
- func (d LegacyDec) MulRoundUpMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) MulTruncate(d2 LegacyDec) LegacyDec
- func (d LegacyDec) MulTruncateMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) MustFloat64() float64
- func (d LegacyDec) Neg() LegacyDec
- func (d LegacyDec) NegMut() LegacyDec
- func (d LegacyDec) Power(power uint64) LegacyDec
- func (d LegacyDec) PowerMut(power uint64) LegacyDec
- func (d LegacyDec) Quo(d2 LegacyDec) LegacyDec
- func (d LegacyDec) QuoInt(i Int) LegacyDec
- func (d LegacyDec) QuoInt64(i int64) LegacyDec
- func (d LegacyDec) QuoInt64Mut(i int64) LegacyDec
- func (d LegacyDec) QuoIntMut(i Int) LegacyDec
- func (d LegacyDec) QuoMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) QuoRoundUp(d2 LegacyDec) LegacyDec
- func (d LegacyDec) QuoRoundupMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) QuoTruncate(d2 LegacyDec) LegacyDec
- func (d LegacyDec) QuoTruncateMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) RoundInt() Int
- func (d LegacyDec) RoundInt64() int64
- func (d LegacyDec) Set(d2 LegacyDec) LegacyDec
- func (d LegacyDec) SetInt64(i int64) LegacyDec
- func (d *LegacyDec) Size() int
- func (d LegacyDec) String() string
- func (d LegacyDec) Sub(d2 LegacyDec) LegacyDec
- func (d LegacyDec) SubMut(d2 LegacyDec) LegacyDec
- func (d LegacyDec) TruncateDec() LegacyDec
- func (d LegacyDec) TruncateInt() Int
- func (d LegacyDec) TruncateInt64() int64
- func (d *LegacyDec) Unmarshal(data []byte) error
- func (d *LegacyDec) UnmarshalAmino(bz []byte) error
- func (d *LegacyDec) UnmarshalJSON(bz []byte) error
- type Uint
- func (u Uint) Add(u2 Uint) Uint
- func (u Uint) AddUint64(u2 uint64) Uint
- func (u Uint) BigInt() *big.Int
- func (u Uint) BigIntMut() *big.Int
- func (u Uint) Decr() Uint
- func (u Uint) Equal(u2 Uint) bool
- func (u Uint) GT(u2 Uint) bool
- func (u Uint) GTE(u2 Uint) bool
- func (u Uint) Incr() Uint
- func (u Uint) IsNil() bool
- func (u Uint) IsZero() bool
- func (u Uint) LT(u2 Uint) bool
- func (u Uint) LTE(u2 Uint) bool
- func (u Uint) Marshal() ([]byte, error)
- func (u Uint) MarshalAmino() ([]byte, error)
- func (u Uint) MarshalJSON() ([]byte, error)
- func (u *Uint) MarshalTo(data []byte) (n int, err error)
- func (u Uint) Mod(u2 Uint) Uint
- func (u Uint) Mul(u2 Uint) (res Uint)
- func (u Uint) MulUint64(u2 uint64) (res Uint)
- func (u Uint) Quo(u2 Uint) (res Uint)
- func (u Uint) QuoUint64(u2 uint64) Uint
- func (u *Uint) Size() int
- func (u Uint) String() string
- func (u Uint) Sub(u2 Uint) Uint
- func (u Uint) SubUint64(u2 uint64) Uint
- func (u Uint) Uint64() uint64
- func (u *Uint) Unmarshal(data []byte) error
- func (u *Uint) UnmarshalAmino(bz []byte) error
- func (u *Uint) UnmarshalJSON(bz []byte) error
Examples ¶
Constants ¶
const ( // MaxExponent is the highest exponent supported. Exponents near this range will // perform very slowly (many seconds per operation). MaxExponent = apd.MaxExponent // MinExponent is the lowest exponent supported with the same limitations as // MaxExponent. MinExponent = apd.MinExponent )
const ( // LegacyPrecision number of decimal places LegacyPrecision = 18 // LegacyDecimalPrecisionBits bits required to represent the above precision // Ceiling[Log2[10^Precision - 1]] // Deprecated: This is unused and will be removed LegacyDecimalPrecisionBits = 60 )
const MaxBitLen = 256
MaxBitLen defines the maximum bit length supported bit Int and Uint types.
Variables ¶
var ( ErrInvalidDec = errors.Register(mathCodespace, 1, "invalid decimal") ErrUnexpectedRounding = errors.Register(mathCodespace, 2, "unexpected rounding") ErrNonIntegral = errors.Register(mathCodespace, 3, "value is non-integral") )
var ( // ErrIntOverflow is the error returned when an integer overflow occurs ErrIntOverflow = errors.New("integer overflow") // ErrDivideByZero is the error returned when a divide by zero occurs ErrDivideByZero = errors.New("divide by zero") )
Integer errors
var ( ErrLegacyEmptyDecimalStr = errors.New("decimal string cannot be empty") ErrLegacyInvalidDecimalLength = errors.New("invalid decimal length") ErrLegacyInvalidDecimalStr = errors.New("invalid decimal string") )
Decimal errors
Functions ¶
func FormatDec ¶
FormatDec formats a decimal (as encoded in protobuf) into a value-rendered string following ADR-050. This function operates with string manipulation (instead of manipulating the sdk.Dec object).
func FormatInt ¶
FormatInt formats an integer (encoded as in protobuf) into a value-rendered string following ADR-050. This function operates with string manipulation (instead of manipulating the int or math.Int object).
func LegacyDecApproxEq ¶
func LegacyDecEq ¶
LegacyDecEq intended to be used with require/assert: require.True(DecEq(...))
func LegacyDecsEqual ¶
LegacyDecsEqual return true if two decimal arrays are equal.
func LegacySortableDecBytes ¶
LegacySortableDecBytes returns a byte slice representation of a Dec that can be sorted. Left and right pads with 0s so there are 18 digits to left and right of the decimal point. For this reason, there is a maximum and minimum value for this, enforced by ValidSortableDec.
func LegacyValidSortableDec ¶
LegacyValidSortableDec ensures that a Dec is within the sortable bounds, a Dec can't have a precision of less than 10^-18. Max sortable decimal was set to the reciprocal of SmallestDec.
func Max ¶
func Max[T constraints.Ordered](a, b T, rest ...T) T
func Min ¶
func Min[T constraints.Ordered](a, b T, rest ...T) T
func UintOverflow ¶
UintOverflow returns true if a given unsigned integer overflows and false otherwise.
Types ¶
type Dec ¶ added in v1.5.0
type Dec struct {
// contains filtered or unexported fields
}
Dec is a wrapper struct around apd.Decimal that does no mutation of apd.Decimal's when performing arithmetic, instead creating a new apd.Decimal for every operation ensuring usage is safe.
Using apd.Decimal directly can be unsafe because apd operations mutate the underlying Decimal, but when copying the big.Int structure can be shared between Decimal instances causing corruption. This was originally discovered in regen0-network/mainnet#15.
Example ¶
d := NewDecFromInt64(1) // 1 fmt.Println(d.String()) d = NewDecWithExp(-1234, -3) // -1.234 fmt.Println(d.String()) d = NewDecWithExp(1234, 0) // 1234 fmt.Println(d.String()) d = NewDecWithExp(1234, 1) // 12340 fmt.Println(d.String()) // scientific notation d, err := NewDecFromString("1.23E+4") // 12300 if err != nil { panic(err) } fmt.Println(d.String()) // decimal notation d, err = NewDecFromString("1.234") if err != nil { panic(err) } fmt.Println(d.String())
Output: 1 -1.234 1234 12340 12300 1.234
func NewDecFromInt64 ¶ added in v1.5.0
NewDecFromInt64 converts an int64 to a Dec type. This function is useful for creating Dec values from integer literals or variables, ensuring they can be used in high-precision arithmetic operations defined for Dec types.
Example: - NewDecFromInt64(123) returns a Dec representing the value 123.
func NewDecFromString ¶ added in v1.5.0
NewDecFromString converts a string to a Dec type, supporting standard, scientific, and negative notations. It handles non-numeric values and overflow conditions, returning errors for invalid inputs like "NaN" or "Infinity".
Examples: - "123" -> Dec{123} - "-123.456" -> Dec{-123.456} - "1.23E4" -> Dec{12300} - "NaN" or "Infinity" -> ErrInvalidDec
The internal representation is an arbitrary-precision decimal: Negative × Coeff × 10*Exponent The maximum exponent is 100_000 and must not be exceeded. Following values would be invalid: 1E100001 -> ErrInvalidDec -1E100001 -> ErrInvalidDec 1E-100001 -> ErrInvalidDec
This function is essential for converting textual data into Dec types for numerical operations.
func NewDecWithExp ¶ added in v1.5.0
NewDecWithExp creates a Dec from a coefficient and exponent, calculated as coeff * 10^exp. Useful for precise decimal representations. Although this method can be used with a higher than maximum exponent or lower than minimum exponent, further arithmetic or other method may fail.
Example: - NewDecWithExp(123, -2) -> Dec representing 1.23.
func (Dec) Add ¶ added in v1.5.0
Add returns a new Dec representing the sum of `x` and `y` using returning a new Dec, we use apd.BaseContext. This function ensures that no arguments are mutated during the operation and checks for overflow conditions. If an overflow occurs, an error is returned.
The precision is much higher as long as the max exponent is not exceeded. If the max exponent is exceeded, an error is returned. For example: - 1e100000 + -1e-1 - 1e100000 + 9e100000 - 1e100001 + 0 We can see that in apd.BaseContext the max exponent is defined hence we cannot exceed.
This function wraps any internal errors with a context-specific error message for clarity.
Example ¶
sum, err := NewDecFromInt64(1).Add(NewDecFromInt64(1)) // 1 + 1 = 2 if err != nil { panic(err) } fmt.Println(sum.String()) const maxExp = 100_000 _, err = NewDecWithExp(1, maxExp).Add(NewDecFromInt64(1)) // 1E+1000000 + 1 if err != nil { fmt.Println(err.Error()) } sum, err = NewDecWithExp(1, maxExp).Add(NewDecWithExp(1, maxExp)) // 1E+1000000 + 1E+1000000 if err != nil { panic(err) } fmt.Println(sum.Text('E')) // the max exponent must not be exceeded _, err = NewDecWithExp(1, maxExp+1).Add(NewDecFromInt64(1)) // 1E+1000001 + 1 if err != nil { fmt.Println(err.Error()) } const minExp = -100_000 // same for min exponent _, err = NewDecWithExp(1, minExp-1).Add(NewDecFromInt64(1)) // 1E-1000001 + 1 if err != nil { fmt.Println(err.Error()) } // not even by adding 0 _, err = NewDecWithExp(1, minExp-1).Add(NewDecFromInt64(0)) // 1E-1000001 + 0 if err != nil { fmt.Println(err.Error()) }
Output: 2 2E+100000 add: exponent out of range: invalid decimal add: exponent out of range: invalid decimal add: exponent out of range: invalid decimal
func (Dec) BigInt ¶ added in v1.5.0
BigInt converts x to a *big.Int or returns an error if x cannot fit precisely into an *big.Int.
func (Dec) Cmp ¶ added in v1.5.0
Cmp compares x and y and returns: -1 if x < y 0 if x == y +1 if x > y undefined if d or x are NaN
func (Dec) Equal ¶ added in v1.5.0
Equal checks if the decimal values of x and y are exactly equal. It returns true if both decimals represent the same value, otherwise false.
func (Dec) Int64 ¶ added in v1.5.0
Int64 converts x to an int64 or returns an error if x cannot fit precisely into an int64.
func (Dec) IsNegative ¶ added in v1.5.0
IsNegative returns true if the decimal is negative.
func (Dec) IsPositive ¶ added in v1.5.0
IsPositive returns true if the decimal is positive.
func (Dec) Marshal ¶ added in v1.5.0
Marshal serializes the decimal value into a byte slice in text format. This method represents the decimal in a portable and compact hybrid notation. Based on the exponent value, the number is formatted into decimal: -ddddd.ddddd, no exponent or scientific notation: -d.ddddE±dd
For example, the following transformations are made:
- 0 -> 0
- 123 -> 123
- 10000 -> 10000
- -0.001 -> -0.001
- -0.000000001 -> -1E-9
Returns:
- A byte slice of the decimal in text format.
- An error if the decimal cannot be reduced or marshaled properly.
func (Dec) MarshalJSON ¶ added in v1.5.0
MarshalJSON serializes the Dec struct into a JSON-encoded byte slice using scientific notation.
func (Dec) MarshalTo ¶ added in v1.5.0
MarshalTo encodes the receiver into the provided byte slice and returns the number of bytes written and any error encountered.
func (Dec) Modulo ¶ added in v1.5.0
Modulo computes the remainder of division of x by y using decimal128 precision. It returns an error if y is zero or if any other error occurs during the computation.
Example:
- 7 mod 3 = 1
- 6 mod 3 = 0
Example ¶
sum, err := NewDecFromInt64(7).Modulo(NewDecFromInt64(3)) // 7 mod 3 = 1 if err != nil { panic(err) } fmt.Println(sum.String())
Output: 1
func (Dec) Mul ¶ added in v1.5.0
Mul returns a new Dec with value `x*y` (formatted as decimal128, with 34 digit precision) without mutating any argument and error if there is an overflow.
Example ¶
sum, err := NewDecFromInt64(2).Mul(NewDecFromInt64(3)) // 2 * 3 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecWithExp(125, -2).Mul(NewDecFromInt64(2)) // 1.25 * 2 if err != nil { panic(err) } fmt.Println(sum.String()) const maxExp = 100_000 sum, err = NewDecWithExp(1, maxExp).Mul(NewDecFromInt64(10)) // 1e100000 * 10 -> err if err != nil { fmt.Println(err.Error()) } sum, err = NewDecFromInt64(1).Mul(NewDecFromInt64(0)) // 1 * 0 if err != nil { panic(err) } fmt.Println(sum.String())
Output: 6 2.50 exponent out of range: invalid decimal 0
func (Dec) MulExact ¶ added in v1.5.0
MulExact multiplies two Dec values x and y without rounding, using decimal128 precision. It returns an error if rounding is necessary to fit the result within the 34-digit limit.
Example: - MulExact(Dec{1.234}, Dec{2.345}) -> Dec{2.893}, or ErrUnexpectedRounding if precision exceeded.
Note: - This function does not alter the original Dec values.
Example ¶
sum, err := NewDecFromInt64(2).MulExact(NewDecFromInt64(3)) // 2 * 3 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecWithExp(125, -2).MulExact(NewDecFromInt64(2)) // 1.25 * 2 if err != nil { panic(err) } fmt.Println(sum.String()) const maxExp = 100_000 sum, err = NewDecWithExp(1, maxExp).MulExact(NewDecFromInt64(10)) // 1e100000 * 10 -> err if err != nil { fmt.Println(err.Error()) } a, err := NewDecFromString("0.12345678901234567890123456789012345") // 35 digits after the comma if err != nil { panic(err) } sum, err = a.MulExact(NewDecFromInt64(1)) if err != nil { fmt.Println(err.Error()) } sum, err = a.MulExact(NewDecFromInt64(0)) if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(1).MulExact(NewDecFromInt64(0)) // 1 * 0 if err != nil { panic(err) } fmt.Println(sum.String())
Output: 6 2.50 exponent out of range: invalid decimal unexpected rounding 0E-35 0
func (Dec) NumDecimalPlaces ¶ added in v1.5.0
NumDecimalPlaces returns the number of decimal places in x.
func (Dec) Quo ¶ added in v1.5.0
Quo performs division of x by y using the decimal128 context with 34 digits of precision. It returns a new Dec or an error if the division is not feasible due to constraints of decimal128.
Within Quo half up rounding may be performed to match the defined precision. If this is unwanted, QuoExact should be used instead.
Key error scenarios: - Division by zero (e.g., `123 / 0` or `0 / 0`) results in ErrInvalidDec. - Non-representable values due to extreme ratios or precision limits.
Examples: - `0 / 123` yields `0`. - `123 / 123` yields `1.000000000000000000000000000000000`. - `-123 / 123` yields `-1.000000000000000000000000000000000`. - `4 / 9` yields `0.4444444444444444444444444444444444`. - `5 / 9` yields `0.5555555555555555555555555555555556`. - `6 / 9` yields `0.6666666666666666666666666666666667`. - `1e-100000 / 10` yields error.
This function is non-mutative and enhances error clarity with specific messages.
Example ¶
sum, err := NewDecFromInt64(6).Quo(NewDecFromInt64(2)) // 6 / 2 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(7).Quo(NewDecFromInt64(2)) // 7 / 2 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(4).Quo(NewDecFromInt64(9)) // 4 / 9 if err != nil { panic(err) } fmt.Println(sum.String()) const minExp = -100_000 sum, err = NewDecWithExp(1, minExp).Quo(NewDecFromInt64(10)) // 1e-100000 / 10 if err != nil { fmt.Println(err.Error()) } sum, err = NewDecFromInt64(1).Quo(NewDecFromInt64(0)) // 1 / 0 -> error if err != nil { fmt.Println(err.Error()) }
Output: 3.000000000000000000000000000000000 3.500000000000000000000000000000000 0.4444444444444444444444444444444444 exponent out of range: invalid decimal division by zero: invalid decimal
func (Dec) QuoExact ¶ added in v1.5.0
QuoExact performs division like Quo and additionally checks for rounding. It returns ErrUnexpectedRounding if any rounding occurred during the division. If the division is exact, it returns the result without error.
This function is particularly useful in financial calculations or other scenarios where precision is critical and rounding could lead to significant errors.
Key error scenarios: - Division by zero (e.g., `123 / 0` or `0 / 0`) results in ErrInvalidDec. - Rounding would have occurred, which is not permissible in this context, resulting in ErrUnexpectedRounding.
Examples: - `0 / 123` yields `0` without rounding. - `123 / 123` yields `1.000000000000000000000000000000000` exactly. - `-123 / 123` yields `-1.000000000000000000000000000000000` exactly. - `1 / 9` yields error for the precision limit - `1e-100000 / 10` yields error for crossing the lower exponent limit. - Any division resulting in a non-terminating decimal under decimal128 precision constraints triggers ErrUnexpectedRounding.
This function does not mutate any arguments and wraps any internal errors with a context-specific error message for clarity.
Example ¶
sum, err := NewDecFromInt64(6).QuoExact(NewDecFromInt64(2)) // 6 / 2 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(7).QuoExact(NewDecFromInt64(2)) // 7 / 2 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(4).QuoExact(NewDecFromInt64(9)) // 4 / 9 -> error if err != nil { fmt.Println(err.Error()) } const minExp = -100_000 sum, err = NewDecWithExp(1, minExp).QuoExact(NewDecFromInt64(10)) // 1e-100000 / 10 -> error if err != nil { fmt.Println(err.Error()) } sum, err = NewDecFromInt64(1).QuoExact(NewDecFromInt64(0)) // 1 / 0 -> error if err != nil { fmt.Println(err.Error()) }
Output: 3.000000000000000000000000000000000 3.500000000000000000000000000000000 unexpected rounding exponent out of range: invalid decimal division by zero: invalid decimal
func (Dec) QuoInteger ¶ added in v1.5.0
QuoInteger performs integer division of x by y, returning a new Dec formatted as decimal128 with 34 digit precision. This function returns the integer part of the quotient, discarding any fractional part, and is useful in scenarios where only the whole number part of the division result is needed without rounding.
Key error scenarios: - Division by zero (e.g., `123 / 0`) results in ErrInvalidDec. - Overflow conditions if the result exceeds the storage capacity of a decimal128 formatted number.
Examples: - `123 / 50` yields `2` (since the fractional part .46 is discarded). - `100 / 3` yields `33` (since the fractional part .3333... is discarded). - `50 / 100` yields `0` (since 0.5 is less than 1 and thus discarded).
The function does not mutate any arguments and ensures that errors are wrapped with specific messages for clarity.
Example ¶
sum, err := NewDecFromInt64(6).QuoInteger(NewDecFromInt64(2)) // 6 / 2 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(7).QuoInteger(NewDecFromInt64(2)) // 7 / 2 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(4).QuoInteger(NewDecFromInt64(9)) // 4 / 9 -> error if err != nil { panic(err) } fmt.Println(sum.String()) const minExp = -100_000 sum, err = NewDecWithExp(1, minExp).QuoInteger(NewDecFromInt64(10)) // 1e-100000 / 10 -> 0 if err != nil { panic(err) } fmt.Println(sum.String()) sum, err = NewDecFromInt64(1).QuoInteger(NewDecFromInt64(0)) // 1 / 0 -> error if err != nil { fmt.Println(err.Error()) }
Output: 3 3 0 0 division by zero: invalid decimal
func (Dec) Reduce ¶ added in v1.5.0
Reduce returns a copy of x with all trailing zeros removed and the number of zeros that were removed. It does not modify the original decimal.
func (Dec) SdkIntTrim ¶ added in v1.5.0
SdkIntTrim rounds the decimal number towards zero to the nearest integer, then converts and returns it as `sdkmath.Int`. It handles both positive and negative values correctly by truncating towards zero. This function returns an ErrNonIntegral error if the resulting integer is larger than the maximum value that `sdkmath.Int` can represent.
func (Dec) Size ¶ added in v1.5.0
Size returns the number of bytes required to encode the Dec value, which is useful for determining storage requirements.
func (Dec) String ¶ added in v1.5.0
String formatted in decimal notation: '-ddddd.dddd', no exponent
func (Dec) Sub ¶ added in v1.5.0
Sub returns a new Dec representing the sum of `x` and `y` using returning a new Dec, we use apd.BaseContext. This function ensures that no arguments are mutated during the operation and checks for overflow conditions. If an overflow occurs, an error is returned.
The precision is much higher as long as the max exponent is not exceeded. If the max exponent is exceeded, an error is returned. For example: - 1e-100001 - 0 - 1e100000 - 1e-1 - 1e100000 - -9e100000 - 1e100001 - 1e100001 (upper limit exceeded) - 1e-100001 - 1e-100001 (lower limit exceeded) We can see that in apd.BaseContext the max exponent is defined hence we cannot exceed.
This function wraps any internal errors with a context-specific error message for clarity.
Example ¶
sum, err := NewDecFromInt64(2).Sub(NewDecFromInt64(1)) // 2 - 1 if err != nil { panic(err) } fmt.Println(sum.String()) const maxExp = 100_000 _, err = NewDecWithExp(1, maxExp).Sub(NewDecFromInt64(1)) // 1E+1000000 - 1 if err != nil { fmt.Println(err.Error()) } sum, err = NewDecWithExp(1, maxExp).Sub(NewDecWithExp(1, maxExp)) // 1E+1000000 - 1E+1000000 if err != nil { panic(err) } fmt.Println(sum.Text('E')) // the max exponent must not be exceeded _, err = NewDecWithExp(1, maxExp+1).Sub(NewDecFromInt64(1)) // 1E+1000001 - 1 if err != nil { fmt.Println(err.Error()) } const minExp = -100_000 // same for min exponent _, err = NewDecWithExp(1, minExp-1).Sub(NewDecFromInt64(1)) // 1E-1000001 - 1 if err != nil { fmt.Println(err.Error()) } // not even by adding 0 _, err = NewDecWithExp(1, minExp-1).Sub(NewDecFromInt64(0)) // 1E-1000001 - 0 if err != nil { fmt.Println(err.Error()) }
Output: 1 0E+100000 sub: exponent out of range: invalid decimal sub: exponent out of range: invalid decimal sub: exponent out of range: invalid decimal
func (Dec) Text ¶ added in v1.5.0
Text converts the floating-point number x to a string according to the given format. The format is one of:
'e' -d.dddde±dd, decimal exponent, exponent digits 'E' -d.ddddE±dd, decimal exponent, exponent digits 'f' -ddddd.dddd, no exponent 'g' like 'e' for large exponents, like 'f' otherwise 'G' like 'E' for large exponents, like 'f' otherwise
If format is a different character, Text returns a "%" followed by the unrecognized.Format character. The 'f' format has the possibility of displaying precision that is not present in the Decimal when it appends zeros (the 'g' format avoids the use of 'f' in this case). All other formats always show the exact precision of the Decimal.
func (*Dec) Unmarshal ¶ added in v1.5.0
Unmarshal parses a byte slice containing a text-formatted decimal and stores the result in the receiver. It returns an error if the byte slice does not represent a valid decimal.
func (*Dec) UnmarshalJSON ¶ added in v1.5.0
UnmarshalJSON implements the json.Unmarshaler interface for the Dec type, converting JSON strings to Dec objects.
type Int ¶
type Int struct {
// contains filtered or unexported fields
}
Int wraps big.Int with a 256 bit range bound Checks overflow, underflow and division by zero Exists in range from -(2^256 - 1) to 2^256 - 1
func NewIntFromBigInt ¶
NewIntFromBigInt constructs Int from big.Int. If the provided big.Int is nil, it returns an empty instance. This function panics if the bit length is > 256. Note, the caller can safely mutate the argument after this function returns.
func NewIntFromBigIntMut ¶ added in v1.2.0
NewIntFromBigIntMut constructs Int from big.Int. If the provided big.Int is nil, it returns an empty instance. This function panics if the bit length is > 256. Note, this function mutate the argument.
func NewIntFromString ¶
NewIntFromString constructs Int from string
func NewIntFromUint64 ¶
NewIntFromUint64 constructs an Int from a uint64.
func NewIntWithDecimal ¶
NewIntWithDecimal constructs Int with decimal Result value is n*10^dec
func (Int) MarshalAmino ¶
MarshalAmino Override Amino binary serialization by proxying to protobuf.
func (Int) MarshalJSON ¶
MarshalJSON defines custom encoding scheme
func (Int) MarshalYAML ¶
MarshalYAML returns the YAML representation.
func (Int) SafeMod ¶ added in v1.3.0
SafeMod returns remainder after dividing with Int and returns an error if division by zero
func (Int) SafeMul ¶ added in v1.3.0
SafeMul multiples Int from another and returns an error if overflow
func (Int) SafeQuo ¶ added in v1.3.0
SafeQuo divides Int with Int and returns an error if division by zero
func (Int) SafeSub ¶ added in v1.3.0
SafeSub subtracts Int from another and returns an error if overflow or underflow
func (Int) ToLegacyDec ¶ added in v1.1.0
ToLegacyDec converts Int to LegacyDec
func (*Int) UnmarshalAmino ¶
func (*Int) UnmarshalJSON ¶
UnmarshalJSON defines custom decoding scheme
type LegacyDec ¶
type LegacyDec struct {
// contains filtered or unexported fields
}
LegacyDec NOTE: never use new(Dec) or else we will panic unmarshalling into the nil embedded big.Int
var LegacyMaxSortableDec LegacyDec
LegacyMaxSortableDec is the largest Dec that can be passed into SortableDecBytes() Its negative form is the least Dec that can be passed in.
func LegacyMaxDec ¶
LegacyMaxDec maximum decimal between two
func LegacyMinDec ¶
LegacyMinDec minimum decimal between two
func LegacyMustNewDecFromStr ¶
LegacyMustNewDecFromStr Decimal from string, panic on error
func LegacyNewDec ¶
LegacyNewDec create a new Dec from integer assuming whole number
func LegacyNewDecFromBigInt ¶
LegacyNewDecFromBigInt create a new Dec from big integer assuming whole numbers CONTRACT: prec <= Precision
func LegacyNewDecFromBigIntWithPrec ¶
LegacyNewDecFromBigIntWithPrec create a new Dec from big integer assuming whole numbers CONTRACT: prec <= Precision
func LegacyNewDecFromInt ¶
LegacyNewDecFromInt create a new Dec from big integer assuming whole numbers CONTRACT: prec <= Precision
func LegacyNewDecFromIntWithPrec ¶
LegacyNewDecFromIntWithPrec create a new Dec from big integer with decimal place at prec CONTRACT: prec <= Precision
func LegacyNewDecFromStr ¶
LegacyNewDecFromStr create a decimal from an input decimal string. valid must come in the form:
(-) whole integers (.) decimal integers
examples of acceptable input include:
-123.456 456.7890 345 -456789
NOTE - An error will return if more decimal places are provided in the string than the constant Precision.
CONTRACT - This function does not mutate the input str.
func LegacyNewDecWithPrec ¶
LegacyNewDecWithPrec create a new Dec from integer with decimal place at prec CONTRACT: prec <= Precision
func LegacyOneDec ¶
func LegacyOneDec() LegacyDec
func LegacySmallestDec ¶
func LegacySmallestDec() LegacyDec
func LegacyZeroDec ¶
func LegacyZeroDec() LegacyDec
func (LegacyDec) ApproxRoot ¶
ApproxRoot returns an approximate estimation of a Dec's positive real nth root using Newton's method (where n is positive). The algorithm starts with some guess and computes the sequence of improved guesses until an answer converges to an approximate answer. It returns `|d|.ApproxRoot() * -1` if input is negative. A maximum number of 100 iterations is used a backup boundary condition for cases where the answer never converges enough to satisfy the main condition.
func (LegacyDec) ApproxSqrt ¶
ApproxSqrt is a wrapper around ApproxRoot for the common special case of finding the square root of a number. It returns -(sqrt(abs(d)) if input is negative.
func (LegacyDec) BigIntMut ¶ added in v1.3.0
BigIntMut converts LegacyDec to big.Int, mutative the input
func (LegacyDec) Ceil ¶
Ceil returns the smallest integer value (as a decimal) that is greater than or equal to the given decimal.
func (LegacyDec) Float64 ¶
Float64 returns the float64 representation of a Dec. Will return the error if the conversion failed.
func (LegacyDec) ImmutOpInt ¶
func (LegacyDec) ImmutOpInt64 ¶
func (LegacyDec) IsInValidRange ¶ added in v1.4.0
IsInValidRange returns true when the value is between the upper limit of (2^256 * 10^18) and the lower limit of -1*(2^256 * 10^18).
func (LegacyDec) IsNegative ¶
func (LegacyDec) IsPositive ¶
func (LegacyDec) MarshalAmino ¶
MarshalAmino Override Amino binary serialization by proxying to protobuf.
func (LegacyDec) MarshalJSON ¶
MarshalJSON marshals the decimal
func (LegacyDec) MarshalYAML ¶
MarshalYAML returns the YAML representation.
func (LegacyDec) MulInt64Mut ¶
func (LegacyDec) MulRoundUp ¶ added in v1.1.0
MulRoundUp multiplication round up at precision end.
func (LegacyDec) MulRoundUpMut ¶ added in v1.1.0
MulRoundUpMut mutable multiplication with round up at precision end.
func (LegacyDec) MulTruncate ¶
MulTruncate multiplication truncate
func (LegacyDec) MulTruncateMut ¶
MulTruncateMut mutable multiplication truncate
func (LegacyDec) MustFloat64 ¶
MustFloat64 returns the float64 representation of a Dec. Would panic if the conversion failed.
func (LegacyDec) QuoInt64Mut ¶
func (LegacyDec) QuoRoundUp ¶
QuoRoundUp quotient, round up
func (LegacyDec) QuoRoundupMut ¶
QuoRoundupMut mutable quotient, round up
func (LegacyDec) QuoTruncate ¶
QuoTruncate quotient truncate
func (LegacyDec) QuoTruncateMut ¶
QuoTruncateMut divides the current LegacyDec value by the provided LegacyDec value, truncating the result.
func (LegacyDec) RoundInt64 ¶
RoundInt64 rounds the decimal using bankers rounding
func (LegacyDec) TruncateDec ¶
TruncateDec truncates the decimals from the number and returns a Dec
func (LegacyDec) TruncateInt ¶
TruncateInt truncates the decimals from the number and returns an Int
func (LegacyDec) TruncateInt64 ¶
TruncateInt64 truncates the decimals from the number and returns an int64
func (*LegacyDec) UnmarshalAmino ¶
func (*LegacyDec) UnmarshalJSON ¶
UnmarshalJSON defines custom decoding scheme
type Uint ¶
type Uint struct {
// contains filtered or unexported fields
}
Uint wraps integer with 256 bit range bound Checks overflow, underflow and division by zero Exists in range from 0 to 2^256-1
func NewUintFromBigInt ¶
NewUintFromBigInt constructs Uint from big.Int Panics if i is negative or wider than 256 bits
func NewUintFromString ¶
NewUintFromString constructs Uint from string Panics if parsed s is negative or wider than 256 bits
func RelativePow ¶
RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b for example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41)
func (Uint) MarshalAmino ¶
MarshalAmino override Amino binary serialization by proxying to protobuf.
func (Uint) MarshalJSON ¶
MarshalJSON defines custom encoding scheme
func (*Uint) UnmarshalAmino ¶
func (*Uint) UnmarshalJSON ¶
UnmarshalJSON defines custom decoding scheme