decimal

January 18, 2025 · View on GitHub

githubb codecovb goreportb godocb licenseb versionb awesomeb

Package decimal implements correctly rounded decimal floating-point numbers for Go. This package is designed specifically for use in transactional financial systems.

Key Features

  • BSON, JSON, XML, SQL - Implements the necessary interfaces for direct compatibility with the mongo-driver/bson, encoding/json, encoding/xml, and database/sql packages.
  • No Heap Allocations - Optimized to avoid heap allocations, preventing garbage collector impact during arithmetic operations.
  • Correct Rounding - For all methods, the result is the one that would be obtained if the true mathematical value were rounded to 19 digits of precision using the half-to-even rounding (a.k.a. "banker's rounding").
  • No Panics - All methods are panic-free, returning errors instead of crashing your application in cases such as overflow or division by zero.
  • Immutability - Once set, a decimal remains constant, ensuring safe concurrent access across goroutines.
  • Simple String Representation - Decimals are represented in a straightforward format avoiding the complexities of scientific or engineering notations.
  • Rigorous Testing - All methods are cross-validated against the cockroachdb/apd and shopspring/decimal packages through extensive fuzz testing.

Getting Started

Installation

To add the decimal package to your Go workspace:

go get github.com/govalues/decimal

Basic Usage

Create decimal values using one of the constructors. After creating a decimal, you can perform various operations as shown below:

package main

import (
    "fmt"
    "github.com/govalues/decimal"
)

func main() {
    // Constructors
    d, _ := decimal.New(8, 0)               // d = 8
    e, _ := decimal.Parse("12.5")           // e = 12.5
    f, _ := decimal.NewFromFloat64(2.567)   // f = 2.567
    g, _ := decimal.NewFromInt64(7, 896, 3) // g = 7.896

    // Arithmetic operations
    fmt.Println(d.Add(e))              // 8 + 12.5
    fmt.Println(d.Sub(e))              // 8 - 12.5
    fmt.Println(d.SubAbs(e))           // abs(8 - 12.5)

    fmt.Println(d.Mul(e))              // 8 * 12.5
    fmt.Println(d.AddMul(e, f))        // 8 + 12.5 * 2.567
    fmt.Println(d.SubMul(e, f))        // 8 - 12.5 * 2.567
    fmt.Println(d.PowInt(2))           // 8²

    fmt.Println(d.Quo(e))              // 8 / 12.5
    fmt.Println(d.AddQuo(e, f))        // 8 + 12.5 / 2.567
    fmt.Println(d.SubQuo(e, f))        // 8 - 12.5 / 2.567
    fmt.Println(d.QuoRem(e))           // 8 div 12.5, 8 mod 12.5
    fmt.Println(d.Inv())               // 1 / 8

    fmt.Println(decimal.Sum(d, e, f))  // 8 + 12.5 + 2.567
    fmt.Println(decimal.Mean(d, e, f)) // (8 + 12.5 + 2.567) / 3
    fmt.Println(decimal.Prod(d, e, f)) // 8 * 12.5 * 2.567

    // Transcendental functions
    fmt.Println(e.Sqrt())              // √12.5
    fmt.Println(e.Exp())               // exp(12.5)
    fmt.Println(e.Expm1())             // exp(12.5) - 1
    fmt.Println(e.Log())               // ln(12.5)
    fmt.Println(e.Log1p())             // ln(12.5 + 1)
    fmt.Println(e.Log2())              // log₂(12.5)
    fmt.Println(e.Log10())             // log₁₀(12.5)
    fmt.Println(e.Pow(d))              // 12.5⁸

    // Rounding to 2 decimal places
    fmt.Println(g.Round(2))            // 7.90
    fmt.Println(g.Ceil(2))             // 7.90
    fmt.Println(g.Floor(2))            // 7.89
    fmt.Println(g.Trunc(2))            // 7.89

    // Conversions
    fmt.Println(f.Int64(9))            // 2 567000000
    fmt.Println(f.Float64())           // 2.567
    fmt.Println(f.String())            // 2.567

    // Formatting
    fmt.Printf("%.2f", f)              // 2.57
    fmt.Printf("%.2k", f)              // 256.70%
}

Documentation

For detailed documentation and additional examples, visit the package documentation. For examples related to financial calculations, see the money package documentation.

Comparison

Comparison with other popular packages:

Featuregovaluescockroachdb/apd v3.2.1shopspring/decimal v1.4.0
Correctly RoundedYesNoNo
SpeedHighMediumLow1
Heap AllocationsNoMediumHigh
Precision19 digitsArbitraryArbitrary
Panic FreeYesYesNo2
MutabilityImmutableMutable1Immutable
Mathematical ContextImplicitExplicitImplicit

Benchmarks

goos: linux
goarch: amd64
pkg: github.com/govalues/decimal-tests
cpu: AMD Ryzen 7 3700C  with Radeon Vega Mobile Gfx 
Test CaseExpressiongovaluescockroachdb/apd v3.2.1shopspring/decimal v1.4.0govalues vs cockroachdbgovalues vs shopspring
Add5 + 616.06n74.88n140.90n+366.22%+777.33%
Mul2 * 316.93n62.20n146.00n+267.40%+762.37%
Quo2 / 4 (exact)59.52n176.95n657.40n+197.30%+1004.50%
Quo2 / 3 (inexact)391.60n976.80n2962.50n+149.39%+656.42%
PowInt1.1601^{60}950.90n3302.50n4599.50n+247.32%+383.73%
PowInt1.0160001^{600}3.45µ10.67µ18.67µ+209.04%+440.89%
PowInt1.0016000001^{6000}5.94µ20.50µ722.22µ+244.88%+12052.44%
Sqrt√23.40µ4.96µ2101.86µ+46.00%+61755.71%
Expexp(0.5)8.35µ39.28µ20.06µ+370.58%+140.32%
Logln(0.5)54.89µ129.01µ151.55µ+135.03%+176.10%
Parse116.52n76.30n136.55n+362.00%+726.82%
Parse123.45647.37n176.90n242.60n+273.44%+412.14%
Parse123456789.123456789085.49n224.15n497.95n+162.19%+482.47%
String15.11n19.57n198.25n+283.21%+3783.07%
String123.45635.78n77.12n228.85n+115.52%+539.51%
String123456789.123456789070.72n239.10n337.25n+238.12%+376.91%
Telco(see specification)137.00n969.40n3981.00n+607.33%+2804.78%

The benchmark results shown in the table are provided for informational purposes only and may vary depending on your specific use case.

Footnotes

  1. decimal package was created simply because shopspring/decimal was too slow and cockroachdb/apd was mutable. 2

  2. shopspring/decimal panics on division by zero.