Skip to content

A small, strict Go package for representing monetary values safely.

License

Notifications You must be signed in to change notification settings

codegrapple/money

Repository files navigation

money

A small, strict Go package for representing monetary values safely.

This package stores money exclusively in minor units (for example cents). Its goal is not flexibility, but correctness.

Design goals

This package takes a narrow position:

  • Monetary values are stored as unsigned integers in minor units.
  • Invalid states are not representable.
  • Programmer errors surface promptly.

Non-goals

This is not a full financial library.

  • No currency metadata or exchange rates
  • No formatting or localization
  • No decimal math
  • No silent rounding

Usage

Create values using minor units:

m := money.New(12345) // 123.45 in a 2-decimal currency

Add and subtract safely:

a := money.New(500)
b := money.New(200)

sum  := a.Add(b) // 700
diff := a.Sub(b) // 300

Subtraction panics if it would go negative:

_ = money.New(100).Sub(money.New(200)) // panic

Multiply using a floating-point factor. Results are always rounded down:

m := money.New(100)

m.Mul(1.25) // 125
m.Mul(1.99) // 199

Negative multipliers are rejected:

m.Mul(-0.5) // panic

Split amounts

Split money into N parts, distributing any remainder starting from the first part:

m := money.New(123)
parts := m.Split(5) // [25, 25, 25, 24, 24]

Zero checks

money.New(0).IsZero() // true

Converting to major units

Conversion to major units is explicit and adapter-based:

type EUR struct{}

func (EUR) MinorToMajor(minor uint64) float64 {
	return float64(minor) / 100
}

m := money.New(12345)
eur := m.ToMajorUnits(EUR{}) // 123.45

When to use this package

Use it when:

  • You need a safe internal representation for money
  • You want arithmetic that cannot silently go wrong
  • You prefer explicit failures over implicit bugs

Avoid it when:

  • You need decimal math or arbitrary precision
  • You want permissive behavior
  • You allow negative monetary values
  • You’re modeling accounting rules directly

About

A small, strict Go package for representing monetary values safely.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages