Basics
Installation
go get github.com/quagmt/udecimal
udecimal requires Go 1.23 or later.
Usage
a := udecimal.MustParse("123.456")
b := udecimal.MustParse("-12.3456")
fmt.Println(a.Add(b))
fmt.Println(a.Sub(b))
fmt.Println(a.Mul(b))
fmt.Println(a.Div(b))
fmt.Println(a.Div(udecimal.MustParse("7")))
// Output:
// 111.1104
// 135.8016
// -1524.1383936
// -10 <nil>
// 17.6365714285714285714 <nil>
Add, Sub and Mul return a Decimal. Div returns (Decimal, error), because the divisor can be zero.
123.456 / 7 has more than 19 decimal places, so the result is truncated to 19. See
Precision and rounding.
Creating values
| Function | Example | Result |
|---|---|---|
Parse(s) |
udecimal.Parse("-0.00007890123456789") |
-0.00007890123456789, nil |
NewFromInt64(coef, prec) |
udecimal.NewFromInt64(-12345, 2) |
-123.45, nil |
NewFromUint64(coef, prec) |
udecimal.NewFromUint64(12345, 2) |
123.45, nil |
NewFromFloat64(f) |
udecimal.NewFromFloat64(1.234) |
1.234, nil |
NewFromHiLo(neg, hi, lo, prec) |
udecimal.NewFromHiLo(true, 0, 123456, 4) |
-12.3456, nil |
prec is the number of decimal places. Parse and the functions that take prec return ErrPrecOutOfRange for
more decimal places than the default precision, which is 19 unless changed.
MustParse, MustFromInt64, MustFromUint64 and MustFromFloat64 panic instead of returning an error. Zero
and One are predefined values, and the zero value of Decimal is 0.
Floats
NewFromFloat64 converts a binary floating-point number, which may not hold every digit you wrote:
udecimal.NewFromFloat64(123456789.1234567890123456789) is 123456789.12345679. Use Parse when the exact
value matters.
See Parsing for the formats Parse accepts.
Arithmetic
| Method | Returns | Returns an error when |
|---|---|---|
Add, Sub, Mul |
Decimal |
never |
Add64, Sub64, Mul64 |
Decimal; the operand is a uint64 |
never |
Div, Div64 |
(Decimal, error) |
the divisor is zero |
QuoRem |
(quotient, remainder Decimal, error); the quotient is an integer |
the divisor is zero |
Mod |
(Decimal, error), the remainder of QuoRem |
the divisor is zero |
PowInt32(e) |
(Decimal, error) |
0 is raised to a negative power |
PowToIntPart(e) |
(Decimal, error); raises to the integer part of the Decimal e |
0 is raised to a negative power, or the integer part of e is beyond ±math.MaxInt32 |
Sqrt |
(Decimal, error) |
the value is negative |
MustDiv, MustMod and MustQuoRem panic instead of returning an error. PowInt is deprecated; use PowInt32,
which handles 0^0 and negative exponents correctly.
fmt.Println(udecimal.MustParse("1.23").QuoRem(udecimal.MustParse("0.5")))
fmt.Println(udecimal.MustParse("1.23").QuoRem(udecimal.MustParse("0")))
// Output:
// 2 0.23 <nil>
// 0 0 can't divide by zero
fmt.Println(udecimal.MustParse("1.21").Sqrt())
fmt.Println(udecimal.MustParse("0").Sqrt())
fmt.Println(udecimal.MustParse("-1.21").Sqrt())
// Output:
// 1.1 <nil>
// 0 <nil>
// 0 can't calculate square root of negative number
Comparison
| Method | Returns |
|---|---|
a.Cmp(b) |
-1, 0 or 1 |
Equal, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual |
bool |
Sign |
-1, 0 or 1 |
IsZero, IsNeg, IsPos |
bool |
udecimal.Max(a, b...), udecimal.Min(a, b...) |
the largest or smallest value |
udecimal.Avg(a, b...) |
the mean, with at most 19 decimal places, like Div |
Equal compares values, so 1.50 equals 1.5.
fmt.Println(udecimal.MustParse("1.23").Cmp(udecimal.MustParse("4.12475")))
fmt.Println(udecimal.MustParse("1.23").Cmp(udecimal.MustParse("1.23")))
fmt.Println(udecimal.MustParse("1.23").Cmp(udecimal.MustParse("0.12475")))
// Output:
// -1
// 0
// 1
fmt.Println(udecimal.Avg(udecimal.MustParse("1"), udecimal.MustParse("2"), udecimal.MustParse("4")))
// Output:
// 2.3333333333333333333
Sign and precision
Abs returns the absolute value and Neg the negated value. a.CopySign(b) returns a with the sign of b.
udecimal.Parts(d) returns the integer part and the fractional part of d, which add up to d. The fractional part
has the sign of d, so Parts(-0.5) returns 0 and -0.5. Prec (an int) and PrecUint (a uint8) return
the number of decimal places.
fmt.Println(udecimal.Parts(udecimal.MustParse("123.456")))
fmt.Println(udecimal.Parts(udecimal.MustParse("-123.456")))
// Output:
// 123 0.456
// -123 -0.456
fmt.Println(udecimal.MustParse("-10").CopySign(udecimal.MustParse("2")))
fmt.Println(udecimal.MustParse("10").CopySign(udecimal.MustParse("-3")))
// Output:
// 10
// -10
Conversion
| Method | Returns |
|---|---|
String |
the shortest form, without trailing zeros |
StringFixed(prec) |
at least prec decimal places, padded with zeros; it doesn't round |
Int64 |
the integer part as an int64; an error if it doesn't fit, or if the value is stored as math/big (see How it works) |
InexactFloat64 |
the nearest float64 |
ToHiLo |
the sign, the 128-bit coefficient as two uint64 values, and the precision; ok is false if the value is stored as math/big, which includes every result computed with math/big |
fmt.Println(udecimal.MustParse("1").StringFixed(2))
fmt.Println(udecimal.MustParse("1.23").StringFixed(4))
fmt.Println(udecimal.MustParse("-1.230000").StringFixed(5))
// Output:
// 1.00
// 1.2300
// -1.23000
fmt.Println(udecimal.MustParse("1.23").Int64())
fmt.Println(udecimal.MustParse("1234567890123456789.1234567890123456789").Int64())
fmt.Println(udecimal.MustParse("-1234567890123456789.1234567890123456789").Int64())
fmt.Println(udecimal.MustParse("0.123").Int64())
fmt.Println(udecimal.MustParse("-0.123").Int64())
fmt.Println(udecimal.MustParse("12345678901234567890123456.123456").Int64())
// Output:
// 1 <nil>
// 1234567890123456789 <nil>
// -1234567890123456789 <nil>
// 0 <nil>
// 0 <nil>
// 0 integer part is too large to fit in int64
Errors
All errors are package variables, so you can check them with errors.Is:
| Error | Returned by |
|---|---|
ErrPrecOutOfRange |
Parse, NewFromInt64, NewFromUint64, NewFromHiLo and NewFromFloat64, for more decimal places than the default precision |
ErrEmptyString |
Parse("") |
ErrMaxStrLen |
Parse of a string longer than 200 characters |
ErrInvalidFormat |
Parse of a string that isn't a decimal number, and NewFromFloat64 of NaN or an infinity |
ErrDivideByZero |
Div, Div64, Mod and QuoRem with a zero divisor |
ErrZeroPowNegative |
PowInt32 and PowToIntPart when 0 is raised to a negative power |
ErrExponentTooLarge |
PowToIntPart when the integer part of the exponent is beyond ±math.MaxInt32 |
ErrSqrtNegative |
Sqrt of a negative value |
ErrIntPartOverflow |
Int64 when the integer part doesn't fit |
ErrInvalidBinaryData |
UnmarshalBinary of data in the wrong layout |
The text decoders (UnmarshalJSON, UnmarshalText and Scan) wrap the errors from Parse, and NewFromFloat64
wraps its own errors, so use errors.Is instead of ==.
_, err := udecimal.MustParse("1").Div(udecimal.Zero)
fmt.Println(errors.Is(err, udecimal.ErrDivideByZero))
_, err = udecimal.Parse("1e5")
fmt.Println(errors.Is(err, udecimal.ErrInvalidFormat))
// Output:
// true
// true
Apart from the Must* functions, only SetDefaultPrecision and SetDefaultParseMode panic, and only for an
invalid argument.