Skip to content

decimal ​

Before You Start

  • Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Data Types · Read time: about 10 min

Repository: shopspring/decimal: Arbitrary-precision fixed-point decimal numbers in go (github.com)

Documentation: decimal package - github.com/shopspring/decimal - Go Packages

Introduction ​

A decimal floating point utility library written in Go with the following features:

  • Zero value is 0, safe to use without initialization
  • Addition, subtraction, multiplication without loss of precision
  • Division with specified precision
  • Database/sql serialization/deserialization
  • JSON and XML serialization/deserialization

Installation ​

go get github.com/shopspring/decimal

Quick Start ​

go
package main

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

func main() {
  price, err := decimal.NewFromString("136.02")
  if err != nil {
    panic(err)
  }

  quantity := decimal.NewFromInt(3)

  fee, _ := decimal.NewFromString(".035")
  taxRate, _ := decimal.NewFromString(".08875")

  subtotal := price.Mul(quantity)

  preTax := subtotal.Mul(fee.Add(decimal.NewFromFloat(1)))

  total := preTax.Mul(taxRate.Add(decimal.NewFromFloat(1)))

  fmt.Println("Subtotal:", subtotal)                      // Subtotal: 408.06
  fmt.Println("Pre-tax:", preTax)                         // Pre-tax: 422.3421
  fmt.Println("Taxes:", total.Sub(preTax))                // Taxes: 37.482861375
  fmt.Println("Total:", total)                            // Total: 459.824961375
  fmt.Println("Tax rate:", total.Sub(preTax).Div(preTax)) // Tax rate: 0.08875
}

Complete Example ​

The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.

go
package main

import "fmt"

func main() {
	// Store money in cents to avoid binary floating point errors
	price := int64(1999) // 19.99
	count := int64(3)
	total := price * count

	fmt.Printf("%d.%02d\n", total/100, total%100)

	// The float64 version shows why this matters
	a, b := 0.1, 0.2
	fmt.Println(a + b)
}

Expected output:

text
59.97
0.30000000000000004

Common Pitfalls ​

  • float64 cannot represent 0.1 exactly. 0.1 + 0.2 is not 0.3; money needs integers or a decimal type.
  • Rounding must be explicit. Decide the scale (usually 2 for currency) and round half-up or half-even deliberately.
  • Division needs a scale. decimal.Div divides with a precision; set it or errors accumulate.
  • JSON does not support decimals. Marshal as string (or integer cents) to avoid precision loss.
  • Compare with methods. Use Equal/Cmp instead of == on struct-wrapped values.

Change Log ​

  • 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log. Closed a code block that was left unterminated.

Golang by www.golangdev.cn · Adapted in part from Golang 中文学习文档 (MIT, © 寒江蓑笠翁)