shopspring/decimal provides fixed-point decimal types for Go with exact add, subtract, and multiply. It suits money calculations where float64 rounding is unacceptable.
Overview
decimal is a Go package implementing arbitrary-precision fixed-point decimal numbers. The zero value is usable as zero without initialization, and arithmetic methods return new values instead of mutating receivers, which reduces accidental aliasing compared with some big number APIs.
Operations include addition, subtraction, and multiplication without precision loss, division and square root with configurable rounding precision, and package-level settings that control division precision, power precision, string formatting, JSON marshaling, and decode exponent limits. Serialization supports database/sql, JSON, XML, and MongoDB BSON as Decimal128 with the official Go driver v2.
Install via go get against the GitHub module path. Trade-offs versus float64 and big.Rat matter for monetary amounts, with emphasis on exact string representations for financial splits. It requires Go 1.10 or newer.
Key features
- Fixed-point decimal type for Go
- Immutable arithmetic API
- Configurable division and power precision
- JSON and XML serialization
- database/sql driver support
- MongoDB Decimal128 BSON encoding
- Global formatting and encoding toggles
Use cases
- Monetary amounts without float rounding
- Ledger or billing calculations in Go services
- JSON APIs requiring decimal strings
- Database-backed financial models
- Splitting amounts across three recipients exactly