Documentation ¶
Overview ¶
Package decimal128 provides a 128-bit decimal floating point type.
Index ¶
- Constants
- Variables
- func Compare(d, o Decimal) int
- type Ascending
- type CmpResult
- type Counter
- type Decimal
- func Abs(d Decimal) Decimal
- func Avg(first Decimal, rest ...Decimal) Decimal
- func Ceil(d Decimal) Decimal
- func Count(values []Decimal, counter Counter) Decimal
- func Dot(x, y []Decimal) (sum Decimal)
- func E() Decimal
- func Exp(d Decimal) Decimal
- func Exp10(d Decimal) Decimal
- func Exp2(d Decimal) Decimal
- func Filter(values []Decimal, f Tester) (slice []Decimal)
- func Floor(d Decimal) Decimal
- func FromFloat(f *big.Float) Decimal
- func FromFloat32(f float32) Decimal
- func FromFloat64(f float64) Decimal
- func FromInt(i *big.Int) Decimal
- func FromInt32(i int32) Decimal
- func FromInt64(i int64) Decimal
- func FromRat(r *big.Rat) Decimal
- func FromUint32(i uint32) Decimal
- func FromUint64(i uint64) Decimal
- func Inf(sign int) Decimal
- func Log(d Decimal) Decimal
- func Log10(d Decimal) Decimal
- func Log2(d Decimal) Decimal
- func Max(d, o Decimal) Decimal
- func Min(d, o Decimal) Decimal
- func MustParse(s string) Decimal
- func NaN() Decimal
- func New(sig int64, exp int) Decimal
- func Parse(s string) (Decimal, error)
- func Phi() Decimal
- func Pi() Decimal
- func Reduce(values []Decimal, reducer Reducer, a ...Decimal) Decimal
- func Round(d Decimal) Decimal
- func Sqrt(d Decimal) Decimal
- func Sum(first Decimal, rest ...Decimal) Decimal
- func SumReducer(prev, curr Decimal) Decimal
- func (d Decimal) Abs() Decimal
- func (d Decimal) Add(o Decimal) Decimal
- func (d Decimal) AddWithMode(o Decimal, mode RoundingMode) Decimal
- func (d Decimal) Append(buf []byte, format string) []byte
- func (d Decimal) Canonical() Decimal
- func (d Decimal) Ceil(dp int) Decimal
- func (d Decimal) Cmp(o Decimal) CmpResult
- func (d Decimal) CmpAbs(o Decimal) CmpResult
- func (d *Decimal) Compose(form byte, neg bool, sig []byte, exp int32) error
- func (d Decimal) Decompose(buf []byte) (byte, bool, []byte, int32)
- func (d Decimal) Equal(o Decimal) bool
- func (d Decimal) Float(f *big.Float) *big.Float
- func (d Decimal) Float32() float32
- func (d Decimal) Float64() float64
- func (d Decimal) Floor(dp int) Decimal
- func (d Decimal) Format(f fmt.State, verb rune)
- func (d Decimal) FormatPercentage(prec int) string
- func (d Decimal) GreaterThan(d2 Decimal) bool
- func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool
- func (d Decimal) Int(i *big.Int) *big.Int
- func (d Decimal) Int32() (int32, bool)
- func (d Decimal) Int64() (int64, bool)
- func (d Decimal) IsInf(sign int) bool
- func (d Decimal) IsNaN() bool
- func (d Decimal) IsNegative() bool
- func (d Decimal) IsPositive() bool
- func (d Decimal) IsZero() bool
- func (d Decimal) LessThan(d2 Decimal) bool
- func (d Decimal) LessThanOrEqual(d2 Decimal) bool
- func (d Decimal) MarshalBinary() ([]byte, error)
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) MarshalText() ([]byte, error)
- func (d Decimal) Mul(o Decimal) Decimal
- func (d Decimal) MulWithMode(o Decimal, mode RoundingMode) Decimal
- func (d Decimal) Neg() Decimal
- func (d Decimal) Payload() Payload
- func (d Decimal) Percentage() string
- func (d Decimal) Pow(o Decimal) Decimal
- func (d Decimal) PowWithMode(o Decimal, mode RoundingMode) Decimal
- func (d Decimal) Quo(o Decimal) Decimal
- func (d Decimal) QuoRem(o Decimal) (Decimal, Decimal)
- func (d Decimal) QuoRemWithMode(o Decimal, mode RoundingMode) (Decimal, Decimal)
- func (d Decimal) QuoWithMode(o Decimal, mode RoundingMode) Decimal
- func (d Decimal) Rat(r *big.Rat) *big.Rat
- func (d Decimal) Round(dp int, mode RoundingMode) Decimal
- func (d *Decimal) Scan(f fmt.ScanState, verb rune) error
- func (d Decimal) Sign() int
- func (d Decimal) Signbit() bool
- func (d Decimal) String() string
- func (d Decimal) Sub(o Decimal) Decimal
- func (d Decimal) SubWithMode(o Decimal, mode RoundingMode) Decimal
- func (d Decimal) Uint32() (uint32, bool)
- func (d Decimal) Uint64() (uint64, bool)
- func (d *Decimal) UnmarshalBinary(data []byte) error
- func (d *Decimal) UnmarshalJSON(data []byte) error
- func (d *Decimal) UnmarshalText(data []byte) error
- type Descending
- type Payload
- type Reducer
- type RoundingMode
- type Slice
- type Tester
Examples ¶
Constants ¶
const DefaultPow = 1e8
Variables ¶
var ( Zero = FromInt32(0) One = FromInt32(1) Two = FromInt32(2) Hundred = FromInt32(100) )
Functions ¶
func Compare ¶
Compare returns:
-1 if d < o 0 if d == o +1 if d > o
Unlike Decimal.Cmp, Compare considers NaN values to be less than any other values.
Example ¶
package main import ( "fmt" "slices" "github.com/algo-boyz/decimal128" ) func main() { s := []decimal128.Decimal{ decimal128.New(3, 0), decimal128.New(1, 0), decimal128.NaN(), decimal128.Inf(1), decimal128.New(2, 0), decimal128.Inf(-1), } fmt.Println(s) fmt.Println(slices.MinFunc(s, decimal128.Compare)) fmt.Println(slices.MaxFunc(s, decimal128.Compare)) slices.SortFunc(s, decimal128.Compare) fmt.Println(s) }
Output: [3 1 NaN +Inf 2 -Inf] NaN +Inf [NaN -Inf 1 2 3 +Inf]
Types ¶
type CmpResult ¶
type CmpResult int8
CmpResult represents the result from comparing two Decimals. When the values being compared aren't NaNs, the integer value of the CmpResult will be:
-1 if lhs < rhs 0 if lhs == rhs +1 if lhs > rhs
The Equal, Greater, and Less methods can also be used to determine the result. If either value is a NaN, then these methods will still behave correctly.
func (CmpResult) Equal ¶
Equal returns whether this CmpResult represents that the two Decimals were equal to each other. This method will handle when one of the values being compared was a NaN.
type Decimal ¶
type Decimal struct {
// contains filtered or unexported fields
}
Decimal represents a 128-bit decimal floating point value. The zero value for Decimal is the number +0.0.
func Ceil ¶
Ceil returns the least integer value greater than or equal to d.
Ceil is equivalent to:
d.Ceil(0)
func Floor ¶
Floor returns the greatest integer value less than or equal to d.
Floor is equivalent to:
d.Floor(0)
func Inf ¶
Inf returns a new Decimal set to positive infinity if sign >= 0, or negative infinity if sign < 0.
func MustParse ¶
MustParse is like Parse but panics if the provided string cannot be parsed, instead of returning an error.
func New ¶
New returns a new Decimal with the provided significand and exponent.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { fmt.Println(decimal128.New(3, -2)) fmt.Println(decimal128.New(3, 0)) fmt.Println(decimal128.New(3, 2)) }
Output: 0.03 3 300
func Parse ¶
Parse parses a Decimal value from the string provided. Parse accepts decimal floating point syntax. An underscore character '_' may appear between digits as a separator. Parse also recognises the string "NaN", and the (possibly signed) strings "Inf" and "Infinity", as their respective special floating point values. It ignores case when matching.
If s is not syntactically well-formed, Parse returns an error that can be compared to strconv.ErrSyntax via errors.Is.
If the value is too precise to fit in a Decimal the result is rounded using the DefaultRoundingMode. If the value is greater than the largest possible Decimal value, Parse returns ±Inf and an error that can be compared to strconv.ErrRange via errors.Is.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x, _ := decimal128.Parse("123.456") y, _ := decimal128.Parse("123_456.789e10") inf, _ := decimal128.Parse("-Inf") nan, _ := decimal128.Parse("NaN") fmt.Println(x) fmt.Println(y) fmt.Println(inf) fmt.Println(nan) }
Output: 123.456 1.23456789e+15 -Inf NaN
func Round ¶
Round returns the nearest integer, rounding half away from zero.
Round is equivalent to:
d.Round(0, decimal128.ToNearestAway)
func SumReducer ¶
func (Decimal) Add ¶
Add adds d and o, rounded using the DefaultRoundingMode, and returns the result.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(3, 0) y := decimal128.New(2, -1) fmt.Printf("%g + %g = %g\n", x, y, x.Add(y)) }
Output: 3 + 0.2 = 3.2
func (Decimal) AddWithMode ¶
func (d Decimal) AddWithMode(o Decimal, mode RoundingMode) Decimal
AddWithMode adds d and o, rounding using the provided rounding mode, and returns the result.
func (Decimal) Append ¶
Append formats the Decimal according to the provided format specifier and appends the result to the provided byte slice, returning the updated byte slice. The format specifier can be any value supported by Decimal.Format, without the leading %.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(3, 0) b := x.Append(nil, "010.5f") fmt.Printf("%s\n", b) }
Output: 0003.00000
func (Decimal) Canonical ¶
Canonical returns the result of converting d into its canonical representation. Many values have multiple possible ways of being represented as a Decimal. Canonical converts each of these into a single representation.
If d is ±Inf or NaN, the canonical representation consists of only the bits required to represent the respective special floating point value, with all other bits set to 0. For NaN values this also removes any payload it may have had.
If d is finite, the canonical representation is calculated as the representation with an exponent closest to zero that still accurately stores all non-zero digits the value has.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(123, -1) y := decimal128.New(1230, -2) fmt.Printf("%g, %g\n", x, y) fmt.Printf("%t, %t\n", x.Equal(y), x == y) x = x.Canonical() y = y.Canonical() fmt.Printf("%g, %g\n", x, y) fmt.Printf("%t, %t\n", x.Equal(y), x == y) }
Output: 12.3, 12.3 true, false 12.3, 12.3 true, true
func (Decimal) Ceil ¶
Ceil returns the least Decimal value greater than or equal to d that has no digits after the specified number of decimal places.
The value of dp affects how many digits after the decimal point the Decimal would have if it were printed in decimal notation (for example, by the '%f' verb in Format). It can be zero to return an integer, and can also be negative to round off digits before the decimal point.
NaN and infinity values are left untouched.
func (Decimal) Cmp ¶
Cmp compares two Decimals and returns a CmpResult representing whether the two values were equal, the left-hand side was greater than the right-hand side, or the left-hand side was less than the right-hand side.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(1, 0) y := decimal128.New(2, 0) r := x.Cmp(y) fmt.Printf("%g < %g = %t\n", x, y, r.Less()) fmt.Printf("%g == %g = %t\n", x, y, r.Equal()) fmt.Printf("%g > %g = %t\n", x, y, r.Greater()) }
Output: 1 < 2 = true 1 == 2 = false 1 > 2 = false
func (Decimal) CmpAbs ¶
CmpAbs compares the absolute value of two Decimals and returns a CmpResult representing whether the two values were equal, the left-hand side was greater than the right-hand side, or the left-hand side was less than the right-hand side.
func (*Decimal) Compose ¶
Compose sets d to the value represented by the parts provided as arguments. The arguments consist of:
- a byte form value that should be set to 0 for finite values, 1 for infinite values, or 2 for values which are NaN
- a bool value that should be set to true when the value is negative, false otherwise
- a byte slice that should be set to the significand of the value as a big endian integer
- an int32 exponent
If the value represented by the parts in the arguments are outside the range of a Decimal an error is returned. Compose implements the composer interface used by the database/sql package to read and write decimal values.
func (Decimal) Decompose ¶
Decompose returns the state of d in parts. The returned values consist of:
- a byte form value set to 0 when the value is finite, 1 when the value is infinite, or 2 when the value is NaN
- a bool value set to true if the value is negative, false otherwise
- a byte slice containing the significand of the value as a big endian integer
- an int32 exponent
If the provided buf has sufficient capacity, it may be returned as the significand with the correct value and length set. Decompose implements the decomposer interface used by the database/sql package to read and write decimal values.
func (Decimal) Float ¶
Float converts d into a big.Float. If a non-nil argument f is provided, Float stores the result in f instead of allocating a new big.Float. It panics if d is NaN.
func (Decimal) Floor ¶
Floor returns the greatest Decimal value less than or equal to d that has no digits after the specified number of decimal places.
The value of dp affects how many digits after the decimal point the Decimal would have if it were printed in decimal notation (for example, by the '%f' verb in Format). It can be zero to return an integer, and can also be negative to round off digits before the decimal point.
NaN and infinity values are left untouched.
func (Decimal) Format ¶
Format implements the fmt.Formatter interface. It supports the verbs 'e', 'E', 'f', 'F', 'g', 'G', and 'v', along with the format flags '+', '-', '#', ' ', and '0' and custom width and precision values. Decimal values interpret the format value the same way float32 and float64 does.
func (Decimal) FormatPercentage ¶
func (Decimal) GreaterThan ¶
GreaterThan (GT) returns true when d is greater than d2.
func (Decimal) GreaterThanOrEqual ¶
GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.
func (Decimal) Int ¶
Int converts d into a big.Int, truncating towards zero. If a non-nil argument i is provided, Int stores the result in i instead of allocating a new big.Int. It panics if d is NaN or infinite.
func (Decimal) Int32 ¶
Int32 converts d into an int32, truncating towards zero. If the result is outside the range of an int32 the returned value will be either math.MinInt32 or math.MaxInt32 depending on the sign of the result and the boolean value will be false. Otherwise the boolean value will be true. It panics if d is NaN.
func (Decimal) Int64 ¶
Int64 converts d into an int64, truncating towards zero. If the result is outside the range of an int64 the returned value will be either math.MinInt64 or math.MaxInt64 depending on the sign of the result and the boolean value will be false. Otherwise the boolean value will be true. It panics if d is NaN.
func (Decimal) IsInf ¶
IsInf reports whether d is an infinity. If sign > 0, IsInf reports whether d is positive infinity. If sign < 0, IsInf reports whether d is negative infinity. If sign == 0, IsInf reports whether d is either infinity.
func (Decimal) IsZero ¶
IsZero reports whether the Decimal is equal to zero. This method will return true for both positive and negative zero.
func (Decimal) LessThanOrEqual ¶
LessThanOrEqual (LTE) returns true when d is less than or equal to d2.
func (Decimal) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface. It marshals the Decimal into IEEE 754 format.
func (Decimal) MarshalJSON ¶
MarshalJSON implements the encoding/json.Marshaler interface.
func (Decimal) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface.
func (Decimal) Mul ¶
Mul multiplies d and o, rounding using the DefaultRoundingMode, and returns the result.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(3, 0) y := decimal128.New(2, -1) fmt.Printf("%g * %g = %g\n", x, y, x.Mul(y)) }
Output: 3 * 0.2 = 0.6
func (Decimal) MulWithMode ¶
func (d Decimal) MulWithMode(o Decimal, mode RoundingMode) Decimal
MulWithMode multiplies d and o, rounding using the provided rounding mode, and returns the result.
func (Decimal) Payload ¶
Payload returns the first 64 bits of the payload of a NaN. If the NaN was generated by an operation in this package, the contents of the payload provides information about what kind of operation was being performed that lead to the NaN being generated. Payload panics if d is not a NaN.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { zero := decimal128.Decimal{} x := zero.Quo(zero) fmt.Printf("%g generated by %v\n", x, x.Payload()) }
Output: NaN generated by Quo(Zero, Zero)
func (Decimal) Percentage ¶
func (Decimal) Pow ¶
Pow raises d to the power of o, rounding using the DefaultRoundingMode, and returns the result.
func (Decimal) PowWithMode ¶
func (d Decimal) PowWithMode(o Decimal, mode RoundingMode) Decimal
PowWithMode raises d to the power of o, rounding using the provided rounding mode, and returns the result.
func (Decimal) Quo ¶
Quo divides d by o, rounding using the DefaultRoundingMode, and returns the result.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(152, -1) y := decimal128.New(5, 0) fmt.Printf("%g / %g = %g\n", x, y, x.Quo(y)) }
Output: 15.2 / 5 = 3.04
func (Decimal) QuoRem ¶
QuoRem divides d by o, rounding using the DefaultRoundingMode, and returns the result as an integer quotient and a remainder.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(152, -1) y := decimal128.New(5, 0) q, r := x.QuoRem(y) fmt.Printf("%g / %g = (%g, %g)\n", x, y, q, r) }
Output: 15.2 / 5 = (3, 0.2)
func (Decimal) QuoRemWithMode ¶
func (d Decimal) QuoRemWithMode(o Decimal, mode RoundingMode) (Decimal, Decimal)
QuoRem divides d by o, rounding using the provided rounding mode, and returns the result as an integer quotient and a remainder.
func (Decimal) QuoWithMode ¶
func (d Decimal) QuoWithMode(o Decimal, mode RoundingMode) Decimal
QuoWithMode divides d by o, rounding using the provided rounding mode, and returns the result.
func (Decimal) Rat ¶
Rat converts d into a big.Rat. If a non-nil argument r is provided, Rat stores the result in r instead of allocating a new big.Rat. It panics if d is NaN or infinite.
func (Decimal) Round ¶
func (d Decimal) Round(dp int, mode RoundingMode) Decimal
Round rounds (or quantises) a Decimal value to the specified number of decimal places using the rounding mode provided.
The value of dp affects how many digits after the decimal point the Decimal would have if it were printed in decimal notation (for example, by the '%f' verb in Format). It can be zero to round off all digits after the decimal point and return an integer, and can also be negative to round off digits before the decimal point.
NaN and infinity values are left untouched.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(123456, -3) fmt.Println("unrounded:", x) fmt.Println("+2 places:", x.Round(2, decimal128.DefaultRoundingMode)) fmt.Println(" 0 places:", x.Round(0, decimal128.DefaultRoundingMode)) fmt.Println("-2 places:", x.Round(-2, decimal128.DefaultRoundingMode)) }
Output: unrounded: 123.456 +2 places: 123.46 0 places: 123 -2 places: 100
func (*Decimal) Scan ¶
Scan implements the fmt.Scanner interface. It supports the verbs 'e', 'E', 'f', 'F', 'g', 'G', and 'v'.
func (Decimal) Sub ¶
Sub subtracts o from d, rounding using the DefaultRoundingMode, and returns the result.
Example ¶
package main import ( "fmt" "github.com/algo-boyz/decimal128" ) func main() { x := decimal128.New(3, 0) y := decimal128.New(2, -1) fmt.Printf("%g - %g = %g\n", x, y, x.Sub(y)) }
Output: 3 - 0.2 = 2.8
func (Decimal) SubWithMode ¶
func (d Decimal) SubWithMode(o Decimal, mode RoundingMode) Decimal
SubWithMode subtracts o from d, rounding using the provided rounding mode, and returns the result.
func (Decimal) Uint32 ¶
Uint32 converts d into a uint32, truncating towards zero. If the result is outside the range of a uint32 the returned value will be either 0 or math.MaxUint32 depending on the sign of the result and the boolean value will be false. Otherwise the boolean value will be true. It panics if d is NaN.
func (Decimal) Uint64 ¶
Uint64 converts d into a uint64, truncating towards zero. If the result is outside the range of a uint64 the returned value will be either 0 or math.MaxUint64 depending on the sign of the result and the boolean value will be false. Otherwise the boolean value will be true. It panics if d is NaN.
func (*Decimal) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It unmarshals a Decimal in IEEE 754 format.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON implements the encoding/json.Unmarshaler interface.
func (*Decimal) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface.
type Descending ¶
type Descending []Decimal
func (Descending) Len ¶
func (s Descending) Len() int
func (Descending) Less ¶
func (s Descending) Less(i, j int) bool
func (Descending) Swap ¶
func (s Descending) Swap(i, j int)
type Payload ¶
type Payload uint64
Payload represents the payload value of a NaN decimal. This value can contain additional information about the operation that caused the value to be set to NaN.
type RoundingMode ¶
type RoundingMode uint8
RoundingMode determines how a Decimal value is rounded when the result of an operation is greater than the format can hold.
const ( ToNearestEven RoundingMode = iota // == IEEE 754 roundTiesToEven ToNearestAway // == IEEE 754 roundTiesToAway ToZero // == IEEE 754 roundTowardZero AwayFromZero // no IEEE 754 equivalent ToNegativeInf // == IEEE 754 roundTowardNegative ToPositiveInf // == IEEE 754 roundTowardPositive )
var DefaultRoundingMode RoundingMode = ToNearestEven
DefaultRoundingMode is the rounding mode used by any methods where an alternate rounding mode isn't provided.
func (RoundingMode) String ¶
func (rm RoundingMode) String() string
String returns a string representation of the rounding mode.