decimal
Arbitrary-precision fixed-point decimal numbers for Go, built to avoid the rounding errors of float64 in money and financial math.
Repository Health
Technical Analysis
decimal is a Go library that implements arbitrary-precision fixed-point decimal numbers on top of math/big.Int. Where float64 silently loses precision on values like 0.1, decimal represents numbers exactly as value * 10^exp, so arithmetic on currency and other exact-decimal quantities never drifts. The Decimal type is immutable: every operation (Add, Sub, Mul, Div, Pow, and friends) returns a new value rather than mutating in place, which avoids the aliasing bugs common to big.Int’s in-place API while keeping the calling convention close to Go’s built-in numeric types.
Beyond core arithmetic, the library covers the practical needs of a money/decimal type in a real application: database/sql Scanner and Valuer implementations for reading and writing decimals through database/sql, JSON and XML marshaling/unmarshaling, string parsing with configurable precision, and power/exponent functions with explicit precision control. It has shipped since 2015, is a heavily used dependency across the Go ecosystem for financial and e-commerce code, and its README is candid about tradeoffs versus alternatives like cockroachdb/apd or govalues/decimal for teams that need higher performance or different precision/allocation tradeoffs.
What You Get
- An immutable Decimal type where every arithmetic method (Add, Sub, Mul, Div, Pow, Abs, etc.) returns a new value instead of mutating receivers, eliminating big.Int-style aliasing bugs
- Exact string parsing and formatting via NewFromString/String, plus NewFromFloat, NewFromInt, and NewFromBigInt constructors for converting from other Go numeric types
- database/sql Scanner and Valuer implementations so Decimal columns can be read and written directly through the standard library’s sql package
- JSON and XML (un)marshaling, including a MarshalJSONWithoutQuotes toggle for numeric-vs-string JSON output
- Configurable division precision (DivisionPrecision) and power-of-negative-exponent precision (PowPrecisionNegativeExponent) for controlling how many digits results are computed to
- PowWithPrecision for controlled-precision exponentiation with explicit error returns for undefined cases (0**0, negative base with non-integer exponent, etc.)
Common Use Cases
- Financial calculations - computing subtotals, taxes, fees, and totals in billing or e-commerce systems where float64 rounding would misstate amounts owed
- Persisting money values - storing and retrieving decimal columns through database/sql without manual string conversion
- API payloads - serializing precise decimal quantities (prices, balances, exchange rates) to and from JSON without floating-point precision loss on the wire
- Splitting amounts exactly - dividing a total across N parties with controlled precision and predictable, auditable remainders
- Struct fields for exact quantities - embedding Decimal in domain structs (invoices, ledger entries, orders) where equality and precision must be exact and reproducible
Under The Hood
Architecture decimal.go defines a single core type, Decimal{value *big.Int, exp int32}, representing value * 10^exp; every public operation is a pure function of one or two Decimals plus package-level precision variables (DivisionPrecision, PowPrecisionNegativeExponent) that return a new Decimal rather than mutating either operand, so the whole package is effectively a stateless computation layer over math/big. A second file, decimal-go.go, vendors Go’s internal multiprecision-decimal formatting code (adapted from strconv’s float-to-shortest-decimal routines) purely to support exact float64-to-Decimal string conversion in NewFromFloat, and const.go precomputes a very high-precision ln(10) approximation via constApproximation for use in exponent/logarithm-adjacent operations like Pow. There is no I/O, no state beyond package-level precision knobs, and no dependency graph to speak of beyond the Go standard library, so changing the core Decimal representation would ripple through every method in decimal.go but nothing external.
Tech Stack
The module (go.mod) targets Go 1.10 and declares zero third-party dependencies — everything is built on math/big.Int for arbitrary-precision integers, database/sql/driver for the Scanner/Valuer interfaces, and encoding/json plus encoding/xml for serialization. CI (.github/workflows/ci.yml) runs go build . and go test -v across a matrix from Go 1.10 through the current 1.x release, confirming the library’s long-standing backward-compatibility commitment. There is no build step beyond the standard go build/go test toolchain and no external services or runtime.
Code Quality Testing is extensive: decimal_test.go alone runs to well over 100 test functions covering parsing edge cases, arithmetic identities, JSON/XML round-trips, and precision boundaries, alongside a dedicated decimal_bench_test.go for performance regressions and a decimal_go124_test.go isolating behavior tied to a specific Go version. Error handling is explicit and idiomatic Go: parsing and precision-sensitive operations like NewFromString and PowWithPrecision return (Decimal, error) with descriptive fmt.Errorf messages naming the offending input, rather than panicking or silently returning zero values (a documented exception is Pow, which intentionally returns zero for edge cases and defers to PowWithPrecision when callers need real errors). Exported identifiers carry full godoc comments with runnable examples, and naming is consistent with Go standard-library numeric conventions (New, NewFromInt, NewFromString).
What Makes It Unique
The library’s central design bet — an immutable value type with a big.Int-free public API — directly targets a well-documented Go pitfall: big.Int’s in-place, alias-prone method signatures (z := new(big.Int).Add(x, y)) are easy to misuse in ways that silently corrupt shared values, and the README documents this reasoning explicitly rather than treating immutability as an incidental choice. It also candidly documents its own tradeoffs and points to alternative libraries (cockroachdb/apd for higher performance, govalues/decimal for zero-allocation low-precision use, alpacadecimal for API-compatible high throughput), a level of self-aware positioning that is unusual for a widely-used dependency and reflects a maintainer stance oriented toward correctness-first defaults over raw performance.
Used by 13 apps in this directory
agentgateway
AI Development · Developer Tools
An open source AI-native proxy that secures, observes, and governs agent-to-LLM, agent-to-tool, and agent-to-agent communication through MCP, A2A, and unified LLM routing.
Bytebase
Devops
An open-source database CI/CD and DevSecOps platform — schema migration review, GitOps-driven changes, data masking, and access control across MySQL, PostgreSQL, Oracle, Snowflake, MongoDB, and more.
Coder
Devops · Developer Tools · Code Editors
Self-hosted cloud development environments and AI coding agents — defined in Terraform, connected via WireGuard, automatically shut down when idle.
CubeSandbox
Developer Tools · Security · AI Agents
Instant, concurrent, hardware-isolated MicroVM sandboxes for AI agents — E2B-API compatible, sub-60ms cold starts, and a built-in zero-trust egress proxy, all self-hostable at scale.
Grafana
Monitoring · Analytics
The open-source observability platform that unifies metrics, logs, and traces from any data source into dynamic, queryable dashboards.
infracost
Devops · Developer Tools
Infracost shows cloud cost estimates for Terraform, CloudFormation, and AWS CDK before you deploy — in your terminal, editor, AI coding agent, and pull requests.
OpenMeter
Invoicing Finance · Developer Tools
Open-source metering and billing engine for AI, agentic, and DevTool monetization — ingest usage events in real time and turn them into accurate invoices automatically.
PeerDB
Data Engineering · Databases
Postgres-native ETL that streams change data capture in real time to Snowflake, BigQuery, ClickHouse, S3, and Kafka — up to 10x faster than general-purpose pipelines, managed through a familiar Postgres SQL interface.
Plandex
AI Code Assistants
An open-source, terminal-based AI coding agent built for large tasks and real codebases — with its own version control for plans, a 2M-token effective context window, and self-hosted or cloud deployment.