Choose exact money representations
Choose exact money representations
For a currency with two decimal places, integer minor units can represent amounts exactly. Store currency and scale separately in a real system. Validate input, check overflow and define rounding rules for division or tax calculations. Not every currency uses two fractional digits.
package main
import ( "fmt")
func main() { price := int64(1999) qty := int64(3) total := price * qty fmt.Printf("%d.%02d\n", total/100, total%100)}For these known positive bounded inputs, multiplication is exact. The quotient is whole units and remainder is minor units. This formatting is only for nonnegative amounts; negative amounts need explicit sign handling. General multiplication needs an overflow guard.
Expected output:
59.97Parse a decimal without a binary float
package main
import ( "fmt" "math/big")
func minor(s string) (int64, bool) { r, ok := new(big.Rat).SetString(s) if !ok { return 0, false } r.Mul(r, big.NewRat(100, 1)) if !r.IsInt() || !r.Num().IsInt64() { return 0, false } return r.Num().Int64(), true}func main() { fmt.Println(minor("19.99")) fmt.Println(minor("0.001")) fmt.Println(minor("bad"))}This conversion rejects fractional minor units instead of rounding. It accepts all rational literal formats supported by SetString, not only currency text. For untrusted financial inputs impose a strict decimal grammar and length limit first, and explicitly choose rounding and currency policies.
Expected output:
1999 true0 false0 falseTry it locally
Add 125 and 275 minor units and display the positive total as two decimal places.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 07: Choose exact money representations
Check the lesson objective before moving on.
Why use integer minor units?
What should happen to 0.001 at a two-digit scale under the example policy?