High performance, high precision fixed-point decimal number for financial applications, allocation-free on the fast path.
Documentation, comparisons and benchmarks: https://quagmt.github.io/udecimal/
Supported version: Go >= 1.23
go get github.com/quagmt/udecimal- High Precision: Supports up to 19 decimal places. Extra digits are truncated; rounding is always an explicit call.
- Zero Memory Allocation:
Add,Sub,MulandDivdon't allocate while values fit in 128 bits. See How it works for the exact limits. - Optimized for Speed: For inputs of up to 19 digits,
Add,Sub,MulandDivare 4x8x faster than shopspring/decimal and 1.6x5.7x faster than ericlagergren/decimal on an Apple M4. See Performance for all benchmarks, including cockroachdb/apd and govalues/decimal. - Errors as Values: Operations that can fail, such as
Parse,Div,PowInt32andSqrt, return anerror. Only theMust*helpers,SetDefaultPrecisionandSetDefaultParseModepanic. - Concurrent-Safe: All arithmetic operations return a new
Decimalvalue while keeping the original value unchanged, making it safe to be shared across goroutines. - Correctness: All arithmetic operations are fuzz tested and cross-checked with
shopspring/decimallibrary to ensure correctness. - Versatile Rounding Methods: Includes HALF AWAY FROM ZERO, HALF TOWARD ZERO, AWAY FROM ZERO, and Banker's rounding.
NOTE: This library does not perform implicit rounding. If the result of an operation exceeds the maximum precision, extra digits are truncated. All rounding methods must be explicitly invoked. (see Rounding Methods for more details)
- Checkout documentation for more information.
package main
import (
"fmt"
"github.com/quagmt/udecimal"
)
func main() {
// Create a new decimal number
a, _ := udecimal.NewFromInt64(123456, 3) // a = 123.456
b, _ := udecimal.NewFromInt64(-123456, 4) // b = -12.3456
c, _ := udecimal.NewFromFloat64(1.2345) // c = 1.2345
d, _ := udecimal.Parse("4123547.1234567890123456789") // d = 4123547.1234567890123456789
// Basic arithmetic operations
fmt.Println(a.Add(b)) // 123.456 - 12.3456 = 111.1104
fmt.Println(a.Sub(b)) // 123.456 + 12.3456 = 135.8016
fmt.Println(a.Mul(b)) // 123.456 * -12.3456 = -1524.1383936
fmt.Println(a.Div(b)) // 123.456 / -12.3456 = -10
fmt.Println(a.Div(d)) // 123.456 / 4123547.1234567890123456789 = 0.0000299392722585176
// Rounding
fmt.Println(c.RoundBank(3)) // banker's rounding: 1.2345 -> 1.234
fmt.Println(c.RoundAwayFromZero(2)) // round away from zero: 1.2345 -> 1.24
fmt.Println(c.RoundHAZ(3)) // half away from zero: 1.2345 -> 1.235
fmt.Println(c.RoundHTZ(3)) // half towards zero: 1.2345 -> 1.234
fmt.Println(c.Trunc(2)) // truncate: 1.2345 -> 1.23
fmt.Println(c.Floor()) // floor: 1.2345 -> 1
fmt.Println(c.Ceil()) // ceil: 1.2345 -> 2
// Display
fmt.Println(a.String()) // 123.456
fmt.Println(a.StringFixed(10)) // 123.4560000000
fmt.Println(a.InexactFloat64()) // 123.456
}There are already a couple of decimal libraries available in Go, such as shopspring/decimal, cockroachdb/apd, govalues/decimal, etc. However, each of these libraries has its own limitations, for example:
- shopspring/decimal is great for general-purpose decimal arithmetic because of arbitrary precision. However, it's slow and requires memory allocation for every arithmetic operation. Also in financial applications, arbitrary precision is not always necessary.
- cockroachdb/apd is faster, but its
Divallocates. Also the API is not very intuitive. - govalues/decimal is fast, doesn't allocate in
Add,SubandMul, and is easy to use, but the data range is only limited to 19 digits (include both the integer and fractional parts). Some operations (especially Quo/QuoRem) usually overflow and fallback to use big.Int API, which hurts the performance. Another limitation is that it starts losing precision when the total number of digits exceeds 19.
This library is designed to address these limitations, providing both high performance and allocation-free arithmetic on the fast path while maintaining an acceptable range of precision, which is suitable for most financial applications.
Rounding numbers can often be challenging and confusing due to the variety of methods available. Each method serves specific purposes, and it's common for developers to make mistakes or incorrect assumptions about how rounding should be performed. For example, the result of round(1.45) could be either 1.4 or 1.5, depending on the rounding method used.
This issue is particularly critical in financial applications, where even minor rounding errors can accumulate and lead to significant financial losses. To mitigate such errors, this library intentionally avoids implicit rounding. If the result of an operation exceeds the maximum precision specified by developers beforehand, extra digits are truncated. Developers need to explicitly choose the rounding method they want to use. The supported rounding methods are:
- Banker's rounding or round half to even
- Round away from zero
- Half away from zero (HAZ)
- Half toward zero (HTZ)
package main
import (
"fmt"
"github.com/quagmt/udecimal"
)
func main() {
// Create a new decimal number
a, _ := udecimal.NewFromFloat64(1.345) // a = 1.345
// Rounding
fmt.Println(a.RoundBank(2)) // banker's rounding: 1.345 -> 1.34
fmt.Println(a.RoundAwayFromZero(2)) // round away from zero: 1.345 -> 1.35
fmt.Println(a.RoundHAZ(2)) // half away from zero: 1.345 -> 1.35
fmt.Println(a.RoundHTZ(2)) // half towards zero: 1.345 -> 1.34
}As mentioned above, this library is not always memory allocation free. However, those cases where we need to allocate memory are incredibly rare. To understand why, let's take a look at how the Decimal type is implemented.
The Decimal type represents a fixed-point decimal number. It consists of three components: sign, coefficient, and prec. The number is represented as:
// decimal value = (neg == true ? -1 : 1) * coef * 10^(-prec)
type Decimal struct {
coef bint
neg bool
prec uint8 // 0 <= prec <= 19
}
// Example:
// 123.456 = 123456 * 10^-3
// -> neg = false, coef = 123456, prec = 3
// -123.456 = -123456 / 10^-3
// -> neg = true, coef = 123456, prec = 3You can notice that coef data type is bint, which is a custom data type:
type bint struct {
// For coefficients exceeding u128
bigInt *big.Int
// For coefficients less than 2^128
u128 u128
}The bint type can store coefficients up to 2^128 - 1 using u128. Arithmetic operations with u128 are fast and require no memory allocation. If result of an arithmetic operation exceeds u128 capacity, the whole operation will be performed using big.Int API. Such operations are slower and do involve memory allocation. However, those cases are rare in financial applications due to the extensive range provided by a 128-bit unsigned integer, for example:
-
If precision is 0, the decimal range it can store is:
[-340282366920938463463374607431768211455, 340282366920938463463374607431768211455](approximately -340 to 340 undecillion) -
If precision is 19, the decimal range becomes:
[-34028236692093846346.3374607431768211455, 34028236692093846346.3374607431768211455](approximately -34 to 34 quintillion)
Therefore, in most cases you can expect high performance and no memory allocation when using this library.
This library is inspired by these repositories: