decimal128

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2024 License: 0BSD Imports: 10 Imported by: 3

Documentation

Overview

Package decimal128 provides a 128-bit decimal floating point type.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Append added in v1.3.0

func Append(buf []byte, d Decimal, fmt byte, prec int) []byte

Append appends the string representation of the Decimal to the provided byte slice, as generated by Format, and returns the updated byte slice.

func Compare added in v1.0.0

func Compare(d, o Decimal) int

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/woodsbury/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]

func Format added in v1.3.0

func Format(d Decimal, fmt byte, prec int) string

Format converts the Decimal to a string according to the provided format and precision.

The format is one of 'e', 'E', 'f', 'g', or 'G'.

The precision controls the number of digits in the resulting string. For 'e', 'E', and 'f' it is the number of digits after the decimal point. For 'g' and 'G' it is the maximum number of significant digits. The special precision -1 uses the smallest number of digits necessary to represent the Decimal.

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, GreaterOrEqual, Less, and LessOrEqual 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

func (cr CmpResult) Equal() bool

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.

func (CmpResult) Greater

func (cr CmpResult) Greater() bool

Greater returns whether this CmpResult represents that the value on the left-hand side of the comparison was greater than the value on the right-hand side. This method will handle when one of the values being compared was a NaN.

func (CmpResult) GreaterOrEqual added in v1.1.0

func (cr CmpResult) GreaterOrEqual() bool

GreaterOrEqual returns whether this CmpResult represents that the value on the left-hand side of the comparison was greater than or equal to the value on the right-hand side. This method will handle when one of the values being compared was a NaN.

func (CmpResult) Less

func (cr CmpResult) Less() bool

Less returns whether this CmpResult represents that the value on the left-hand side of the comparison was less than the value on the right-hand side. This method will handle when one of the values being compared was a NaN.

func (CmpResult) LessOrEqual added in v1.1.0

func (cr CmpResult) LessOrEqual() bool

LessOrEqual returns whether this CmpResult represents that the value on the left-hand side of the comparison was less than or equal to the value on the right-hand side. 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 Abs added in v0.2.0

func Abs(d Decimal) Decimal

Abs returns a new Decimal set to the absolute value of d.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(3, 0)
	y := decimal128.New(-3, 0)
	inf := decimal128.Inf(-1)
	nan := decimal128.NaN()
	fmt.Printf("Abs(%g) = %g\n", x, decimal128.Abs(x))
	fmt.Printf("Abs(%g) = %g\n", y, decimal128.Abs(y))
	fmt.Printf("Abs(%g) = %g\n", inf, decimal128.Abs(inf))
	fmt.Printf("Abs(%g) = %g\n", nan, decimal128.Abs(nan))
}
Output:

Abs(3) = 3
Abs(-3) = 3
Abs(-Inf) = +Inf
Abs(NaN) = NaN

func Cbrt added in v1.1.0

func Cbrt(d Decimal) Decimal

Cbrt returns the cube root of d.

func Ceil added in v0.6.0

func Ceil(d Decimal) Decimal

Ceil returns the least integer value greater than or equal to d.

Ceil is equivalent to:

d.Ceil(0)
Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(-123, -2)
	y := decimal128.New(789, -2)
	fmt.Println(decimal128.Ceil(x))
	fmt.Println(decimal128.Ceil(y))
}
Output:

-1
8

func E added in v0.6.0

func E() Decimal

E returns the mathematical constant e.

func Exp added in v0.7.0

func Exp(d Decimal) Decimal

Exp returns e**d, the base-e exponential of d.

func Exp10 added in v0.7.0

func Exp10(d Decimal) Decimal

Exp10 returns 10**d, the base-10 exponential of d.

func Exp2 added in v0.7.0

func Exp2(d Decimal) Decimal

Exp2 returns 2**d, the base-2 exponential of d.

func Expm1 added in v1.1.0

func Expm1(d Decimal) Decimal

Expm1 returns e**d - 1, the base-e exponential of d minus 1. It is more accurate than Exp(d) - 1 when d is near zero.

func Floor added in v0.6.0

func Floor(d Decimal) Decimal

Floor returns the greatest integer value less than or equal to d.

Floor is equivalent to:

d.Floor(0)
Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(-123, -2)
	y := decimal128.New(789, -2)
	fmt.Println(decimal128.Floor(x))
	fmt.Println(decimal128.Floor(y))
}
Output:

-2
7

func Frexp added in v1.2.0

func Frexp(d Decimal) (Decimal, int)

Frexp breaks a finite, non-zero d into a fraction and an integral power of ten. The absolute value of the fraction will be in the interval [0.1, 1).

If d is ±Inf, NaN, or zero the value is returned unchanged and the returned power of ten is zero.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(123, -2)
	frac, exp := decimal128.Frexp(x)
	fmt.Println(frac, exp)
	fmt.Println(decimal128.Ldexp(frac, exp))
}
Output:

0.123 1
1.23

func FromFloat added in v0.2.0

func FromFloat(f *big.Float) Decimal

FromFloat converts f into a Decimal.

func FromFloat32 added in v0.2.0

func FromFloat32(f float32) Decimal

FromFloat32 converts f into a Decimal.

func FromFloat64 added in v0.2.0

func FromFloat64(f float64) Decimal

FromFloat64 converts f into a Decimal.

func FromInt added in v0.2.0

func FromInt(i *big.Int) Decimal

FromInt converts i into a Decimal.

func FromInt32 added in v0.2.0

func FromInt32(i int32) Decimal

FromInt32 converts i into a Decimal.

func FromInt64 added in v0.2.0

func FromInt64(i int64) Decimal

FromInt64 converts i into a Decimal.

func FromRat added in v0.2.0

func FromRat(r *big.Rat) Decimal

FromRat converts r into a Decimal.

func FromUint32 added in v0.2.0

func FromUint32(i uint32) Decimal

FromUint32 converts i into a Decimal.

func FromUint64 added in v0.2.0

func FromUint64(i uint64) Decimal

FromUint64 converts i into a Decimal.

func Inf

func Inf(sign int) Decimal

Inf returns a new Decimal set to positive infinity if sign >= 0, or negative infinity if sign < 0.

func Ldexp added in v1.2.0

func Ldexp(frac Decimal, exp int) Decimal

Ldexp is the inverse of Frexp, returning frac × 10**exp.

func Log added in v0.6.0

func Log(d Decimal) Decimal

Log returns the natural logarithm of d.

func Log10 added in v0.7.0

func Log10(d Decimal) Decimal

Log10 returns the decimal logarithm of d.

func Log1p added in v1.1.0

func Log1p(d Decimal) Decimal

Log1p returns the natural logarithm 1 plus d. It is more accurate than Log(1 + d) when d is near zero.

func Log2 added in v0.7.0

func Log2(d Decimal) Decimal

Log2 returns the binary logarithm of d.

func Max added in v0.10.0

func Max(d, o Decimal) Decimal

Max returns the larger of d or o. If either value is NaN the result is NaN.

func Min added in v0.10.0

func Min(d, o Decimal) Decimal

Min returns the smaller of d or o. If either value is NaN the result is NaN.

func MustParse added in v0.4.0

func MustParse(s string) Decimal

MustParse is like Parse but panics if the provided string cannot be parsed, instead of returning an error.

func NaN

func NaN() Decimal

NaN returns a new Decimal set to the "not-a-number" value.

func New

func New(sig int64, exp int) Decimal

New returns a new Decimal with the provided significand and exponent.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/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

func Parse(s string) (Decimal, error)

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/woodsbury/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 Phi added in v1.0.0

func Phi() Decimal

Phi returns the golden ratio.

func Pi added in v0.6.0

func Pi() Decimal

Pi returns the mathematical constant π.

func Round added in v0.6.0

func Round(d Decimal) Decimal

Round returns the nearest integer, rounding half away from zero.

Round is equivalent to:

d.Round(0, decimal128.ToNearestAway)
Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(-123, -2)
	y := decimal128.New(789, -2)
	fmt.Println(decimal128.Round(x))
	fmt.Println(decimal128.Round(y))
}
Output:

-1
8

func Sqrt added in v0.6.0

func Sqrt(d Decimal) Decimal

Sqrt returns the square root of d.

func Trunc added in v1.2.0

func Trunc(d Decimal) Decimal

Trunc returns the integer value of d.

Trunc is equivalent to:

d.Round(0, decimal128.ToZero)
Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(-123, -2)
	y := decimal128.New(789, -2)
	fmt.Println(decimal128.Trunc(x))
	fmt.Println(decimal128.Trunc(y))
}
Output:

-1
7

func (Decimal) Add

func (d Decimal) Add(o Decimal) Decimal

Add adds d and o, rounded using the DefaultRoundingMode, and returns the result.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/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 added in v0.5.0

func (d Decimal) Append(buf []byte, format string) []byte

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/woodsbury/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 added in v0.12.0

func (d Decimal) Canonical() Decimal

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 ±0, the canonical representation consists of only the sign bit set based on the sign of the value with all other bits set to 0.

If d is finite and non-zero, 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/woodsbury/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 added in v0.6.0

func (d Decimal) Ceil(dp int) Decimal

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.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(123456, -3)
	fmt.Println("unrounded:", x)
	fmt.Println("+2 places:", x.Ceil(2))
	fmt.Println(" 0 places:", x.Ceil(0))
	fmt.Println("-2 places:", x.Ceil(-2))
}
Output:

unrounded: 123.456
+2 places: 123.46
 0 places: 124
-2 places: 200

func (Decimal) Cmp

func (d Decimal) Cmp(o Decimal) CmpResult

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/woodsbury/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

func (d Decimal) CmpAbs(o Decimal) CmpResult

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 added in v0.3.0

func (d *Decimal) Compose(form byte, neg bool, sig []byte, exp int32) error

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 added in v0.3.0

func (d Decimal) Decompose(buf []byte) (byte, bool, []byte, int32)

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) Equal

func (d Decimal) Equal(o Decimal) bool

Equal compares two Decimals and reports whether they are equal.

func (Decimal) Float

func (d Decimal) Float(f *big.Float) *big.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) Float32

func (d Decimal) Float32() float32

Float32 converts d into a float32.

func (Decimal) Float64

func (d Decimal) Float64() float64

Float64 converts d into a float64.

func (Decimal) Floor added in v0.6.0

func (d Decimal) Floor(dp int) Decimal

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.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.New(123456, -3)
	fmt.Println("unrounded:", x)
	fmt.Println("+2 places:", x.Floor(2))
	fmt.Println(" 0 places:", x.Floor(0))
	fmt.Println("-2 places:", x.Floor(-2))
}
Output:

unrounded: 123.456
+2 places: 123.45
 0 places: 123
-2 places: 100

func (Decimal) Format

func (d Decimal) Format(f fmt.State, verb rune)

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) Int added in v0.2.0

func (d Decimal) Int(i *big.Int) *big.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 added in v0.2.0

func (d Decimal) Int32() (int32, bool)

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 added in v0.2.0

func (d Decimal) Int64() (int64, bool)

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

func (d Decimal) IsInf(sign int) bool

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) IsNaN

func (d Decimal) IsNaN() bool

IsNaN reports whether d is a "not-a-number" value.

func (Decimal) IsZero

func (d Decimal) IsZero() bool

IsZero reports whether the Decimal is equal to zero. This method will return true for both positive and negative zero.

func (Decimal) MarshalBinary

func (d Decimal) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface. It marshals the Decimal into IEEE 754 format.

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON implements the encoding/json.Marshaler interface.

func (Decimal) MarshalText

func (d Decimal) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (Decimal) Mul

func (d Decimal) Mul(o Decimal) Decimal

Mul multiplies d and o, rounding using the DefaultRoundingMode, and returns the result.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/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) Neg added in v0.2.0

func (d Decimal) Neg() Decimal

Neg returns d with its sign negated.

func (Decimal) Payload

func (d Decimal) Payload() 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/woodsbury/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) Pow added in v0.8.0

func (d Decimal) Pow(o Decimal) Decimal

Pow raises d to the power of o, rounding using the DefaultRoundingMode, and returns the result.

func (Decimal) PowWithMode added in v0.8.0

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

func (d Decimal) Quo(o Decimal) Decimal

Quo divides d by o, rounding using the DefaultRoundingMode, and returns the result.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/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 added in v0.3.0

func (d Decimal) QuoRem(o Decimal) (Decimal, Decimal)

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/woodsbury/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 added in v0.3.0

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

func (d Decimal) Rat(r *big.Rat) *big.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/woodsbury/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

func (d *Decimal) Scan(f fmt.ScanState, verb rune) error

Scan implements the fmt.Scanner interface. It supports the verbs 'e', 'E', 'f', 'F', 'g', 'G', and 'v'.

func (Decimal) Sign added in v0.3.0

func (d Decimal) Sign() int

Sign returns:

-1 if d <   0
 0 if d is ±0
+1 if d >   0

It panics if d is NaN.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/decimal128"
)

func main() {
	x := decimal128.FromInt64(-5)
	fmt.Printf("% g.Sign() = %d\n", x, x.Sign())
	x = decimal128.FromInt64(0)
	fmt.Printf("% g.Sign() = %d\n", x, x.Sign())
	x = decimal128.FromInt64(5)
	fmt.Printf("% g.Sign() = %d\n", x, x.Sign())
}
Output:

-5.Sign() = -1
 0.Sign() = 0
 5.Sign() = 1

func (Decimal) Signbit added in v0.3.0

func (d Decimal) Signbit() bool

Signbit reports whether d is negative or negative zero.

func (Decimal) String

func (d Decimal) String() string

String returns a string representation of the Decimal value.

func (Decimal) Sub

func (d Decimal) Sub(o Decimal) Decimal

Sub subtracts o from d, rounding using the DefaultRoundingMode, and returns the result.

Example
package main

import (
	"fmt"

	"github.com/woodsbury/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 added in v0.2.0

func (d Decimal) Uint32() (uint32, bool)

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 added in v0.2.0

func (d Decimal) Uint64() (uint64, bool)

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

func (d *Decimal) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It unmarshals a Decimal in IEEE 754 format.

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the encoding/json.Unmarshaler interface.

func (*Decimal) UnmarshalText

func (d *Decimal) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

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.

func (Payload) String

func (p Payload) String() string

String returns a string representation of the payload.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL