num

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: MPL-2.0 Imports: 11 Imported by: 1 module, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

num

go.trippwill.dev/num provides error-carrying decimals for financial and other precision-sensitive Go programs. Arithmetic policies are fixed by the package; applications write calculations without managing decimal contexts.

pnl := exitPrice.Sub(entryPrice).Mul(quantity)
averageCost := totalCost.Div(quantity)
settlement := pnl.Quantize(2)
if !settlement.Ok() {
    return settlement.Err
}

v0.3.0 replaces govalues/decimal with private apd arithmetic, with an allocation-free inline path for small coefficients. It is a breaking release. The complete contract is in the package documentation and the v0.3.0 migration notes.

The library follows a latest-minus-one Go release policy, currently requiring Go 1.26.9 or later within the supported Go 1.26 and 1.27 series. Development and the main CI checks use the Go 1.26.9 toolchain pinned in mise.

Decimal policies

Operation Policy
Construction Preserve finite decimal value and fractional trailing zeros
Add, Sub Exact, retaining the greater operand scale
Mul Exact, retaining the sum of operand scales
Div Automatic significant-digit precision; half-even rounding
Quantize(scale) Half-even rounding or padding to exactly that scale
Comparison Numeric value, independent of stored scale
Serialization Stored decimal, with no additional rounding

Division precision is max(34, meaningfulDigits(left), meaningfulDigits(right)). Meaningful digits count coefficient digits with trailing zeros removed; zero counts as one digit. The 34-digit floor follows the decimal128 convention, and longer operands can increase it. 1.23 and 1.2300 select the same precision. Repeating results succeed, and unnecessary result zeros are removed. Division rounds even a terminating result if it exceeds the selected precision.

Half-even (banker's rounding) is the only rounding mode. Exact arithmetic is bounded to 4,096 coefficient digits, 4,096 integer digits, and fractional scale 0–4,096. Input is limited to 16,384 decoded bytes. Exceeding capacity returns an error rather than silently rounding an exact result.

Values behave immutably, including when copied. Num{} is uninitialized and fails Ok() even though its Err is nil; use num.Zero() for numeric zero. Check Ok() before comparing or using a final calculation. Num is deliberately not comparable with ==.

Presentation with fmt

Display rounding does not change the stored value:

n := num.FromString("123.456789")
fmt.Printf("%.2f\n", n)         // 123.46
fmt.Printf("%10.2f\n", n)       //     123.46
fmt.Printf("%.*f\n", 4, n)      // 123.4568
fmt.Println(n)                 // 123.456789
fmt.Println(n.Quantize(2))      // 123.46, a new value with scale 2

%f and %F default to six fractional places; explicit precision selects the display scale. Numeric output supports +, space, -, and 0 flags. %v and %s preserve the complete representation; %q quotes it. Textual forms support width and alignment but reject precision. Scientific and general verbs such as %e and %g are unsupported. Unsupported or excessive requests produce bounded formatting diagnostics.

Rendering limits are 4,096 fractional places, field width 16,384, and 16,384 output bytes. Rendering uses decimal arithmetic directly, without float64 conversion.

Exact JSON, text, and SQL

JSON output uses bare decimal numbers. Input accepts bare numbers and strings:

n := num.FromString("12345678901234567890.1200")
data, err := json.Marshal(n)
// data is 12345678901234567890.1200

var decoded num.Num
err = json.Unmarshal(data, &decoded)
// Check err for JSON syntax errors and decoded.Ok() for numeric errors.

Direct decoding into Num preserves precision and stored trailing zeros. A consumer that decodes into JavaScript numbers or generic Go float64 values can lose precision. Use Decoder.UseNumber() when handling generic JSON in Go:

decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var raw any
if err := decoder.Decode(&raw); err != nil {
    return err
}
exact := num.FromString(raw.(json.Number).String())

Numeric parse failures in Num.UnmarshalJSON are carried in Num.Err so other struct fields can decode. Text/XML and SQL decoding return errors. SQL Value() returns exact decimal text as a string. NullNum tracks optional presence: JSON null, SQL NULL, and empty text mean absent; a malformed present JSON numeric value remains present with a carried error.

Development and release

mise run verify
mise run precommit
mise run vuln
go test -run '^$' -bench . -benchmem ./...

CI runs unit and race tests on Go 1.26.9 and 1.27.2, with lint on the pinned development toolchain. The required test check aggregates lint, both Go versions, vulnerability scanning, and fuzzing; any failed or skipped dependency fails that check. The pinned govulncheck scans reachable known vulnerabilities, including tests, on PRs, pushes to main, version tags, and weekly runs.

Each of the six fuzz targets runs one million executions per PR or push and 15 million per weekly run, with a ten-minute test timeout. Execution counts avoid Go's duration-limit cancellation race (golang/go#75804). Failed inputs are retained as workflow artifacts for 14 days and should be committed as regression seeds after repair. To run a target locally:

mise exec -- go test . -run '^$' -fuzz '^FuzzNumParseRoundtrip$' -fuzztime 1000000x -parallel 2 -timeout 10m

The module path remains go.trippwill.dev/num. The v0.3.0 changes are intended for a separately reviewed release; a version tag is not implied by these files. After publication, install that version with:

go get go.trippwill.dev/num@v0.3.0

The module is licensed under MPL-2.0. Extraction provenance is recorded in NOTICE.

Documentation

Overview

Package num provides error-carrying decimal arithmetic with fixed policies. Num keeps small coefficients inline and uses private apd storage for larger values and rounded division. It preserves input precision and supports JSON, XML, SQL, text, and Go's fmt package. Values are immutable: assignment, arithmetic, and formatting never mutate another copy. Num is deliberately not comparable; use Num.Equal or Num.Cmp.

Calculations and rounding

Constructors preserve decimal values and fractional trailing zeros. Addition and subtraction are exact and retain the greater operand scale; multiplication is exact and retains the sum of the scales. Capacity errors are reported instead of rounding an exact result to fit.

Division is a rounding boundary. Num.Div rounds half-even (banker's rounding) to max(34, meaningfulDigits(left), meaningfulDigits(right)) significant digits, then removes unnecessary trailing zeros. Meaningful digits are the coefficient digits after removing trailing zeros from a temporary copy; zero counts as one digit. Equivalent values such as 1.23 and 1.2300 select the same precision. The 34-digit floor follows the decimal128 precision convention; it is a package policy rather than a claim that every later calculation will be correctly rounded. Repeating quotients succeed. Terminating quotients exceeding the selected precision also round.

Num.Quantize is an explicit rounding boundary: Quantize(2) rounds half-even or pads zeros to exactly two fractional places. Half-even is the only rounding rule: exact ties choose the even final digit, for either sign. There are no public contexts, rounding-mode parameters, or process-global scale settings. Negative zero becomes positive zero, retaining any intentional fractional scale. Comparisons ignore scale; callers must check Num.Ok before comparing.

Arithmetic carries errors through chains so callers can check the final value:

pnl := exitPrice.Sub(entryPrice).Mul(quantity)
settlement := pnl.Quantize(2)
if !settlement.Ok() {
	return fmt.Errorf("settlement: %w", settlement.Err)
}

Formatting

Formatting selects presentation without changing the value. Num.String, %v, and %s produce the complete stored representation in plain decimal notation. %q quotes that representation. %f and %F select fixed-point display with half-even rounding; their default precision is six fractional places. Width and precision may be supplied dynamically:

n := num.FromString("123.456789")
fmt.Sprintf("%.2f", n)         // "123.46"
fmt.Sprintf("%10.2f", n)       // "    123.46"
fmt.Sprintf("%.*f", 4, n)      // "123.4568"
n.String()                     // "123.456789", unchanged

Numeric formatting supports +, space, -, and 0 flags. Plus takes precedence over space; left alignment takes precedence over zero-padding; zeros follow the sign. Textual forms support width and alignment, but reject precision rather than truncate numeric text. Unsupported verbs (including %e and %g), unsupported flags, and excessive rendering requests produce bounded fmt-style diagnostics. Numeric formatting of invalid values includes an error or uninitialized marker; textual formatting preserves that marker. Formatting never converts through float64.

Capacity and input

Stored values support at most 4,096 coefficient digits (including retained trailing zeros), 4,096 integer digits, and a fractional scale from 0 through 4,096. Positive exponents are normalized to scale zero before validation. Construction and exact arithmetic never silently round to satisfy capacity. Division results must also fit after unnecessary trailing zeros are removed.

Numeric input is limited to 16,384 decoded bytes. Accepted forms are finite decimal literals with an optional sign, fractional part, and decimal exponent; forms such as .5 and 1. are accepted. Embedded or surrounding numeric-text whitespace, underscores, nondecimal syntax, NaN, and infinities are rejected. JSON permits its own surrounding whitespace and standard string escapes. Float64 construction uses the shortest round-trip decimal representation of the supplied float, not its exact binary expansion.

Rendering separately permits up to 4,096 fractional places, field width 16,384, and 16,384 output bytes. Formatting padding may exceed stored-value coefficient capacity because it is presentation only.

Errors and initialization

Num{} is uninitialized, not numeric zero: its Err field is nil but Ok is false. Use Zero for an initialized scale-zero zero. Arithmetic and serialization reject uninitialized operands rather than treating them as zero. Errors from invalid input, capacity limits, invalid quantization scale, and division by zero propagate through arithmetic. Ordinary division or quantization rounding succeeds. Existing carried errors take precedence over later calculation. Use errors.Is to identify ErrInvalidNumericString, ErrUninitialized, ErrInvalidScale, ErrLimitExceeded, or ErrDivisionByZero. Unsupported SQL scan sources report ErrUnsupportedType. Serialization failures wrap ErrMarshalErrorState together with the underlying numeric error.

Serialization and nullable values

JSON output is a bare exact decimal number, including stored trailing zeros. Num.UnmarshalJSON accepts quoted and bare input; parse failures set Num.Err and return nil so unrelated struct fields can still decode. JSON null is invalid for Num. Text/XML and SQL encode exact decimal text without rounding; SQL Num.Value returns a string. Text and SQL decoding return their errors. Failed decoding clears stale numeric state.

Direct JSON decoding into Num preserves precision. Generic Go decoding into any uses float64 by default, and JavaScript numbers use binary floating point; these consumers can lose decimal precision. Go consumers handling generic JSON can call encoding/json.Decoder.UseNumber and pass json.Number.String() to FromString. Output does not switch between strings and numbers by size.

NullNum represents presence separately from numeric validity. JSON null, SQL NULL, and empty text set Valid=false; absent JSON output is null. A present malformed JSON number has Valid=true and a carried Num error. Failed text or SQL decoding returns an error and leaves Valid=false. A missing nullable struct field remains absent. SQL scanning accepts string, []byte, int64, uint64, float64, and float32; float32 is first converted to float64.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string

Error is a sentinel error type for the num package.

const (
	ErrInvalidNumericString Error = "num: invalid numeric string"
	ErrUnsupportedType      Error = "num: unsupported type"
	ErrMarshalErrorState    Error = "num: cannot marshal error-state value"
	ErrUninitialized        Error = "num: uninitialized value"
	ErrInvalidScale         Error = "num: invalid scale"
	ErrLimitExceeded        Error = "num: numeric limit exceeded"
	ErrDivisionByZero       Error = "num: division by zero"
)

func (Error) Error

func (e Error) Error() string

type NullNum

type NullNum struct {
	Num   Num
	Valid bool
}

NullNum represents a Num that may be null.

Example
package main

import (
	"encoding/json"
	"fmt"

	"go.trippwill.dev/num"
)

func main() {
	type Position struct {
		Price  num.Num     `json:"price"`
		Strike num.NullNum `json:"strike"`
	}

	data := []byte(`{"price": 42.50, "strike": null}`)
	var pos Position
	_ = json.Unmarshal(data, &pos)

	fmt.Printf("price=%s strike.valid=%v\n", pos.Price, pos.Strike.Valid)
}
Output:
price=42.50 strike.valid=false

func (NullNum) MarshalJSON

func (nn NullNum) MarshalJSON() ([]byte, error)

MarshalJSON returns JSON null when !Valid, otherwise delegates to Num.MarshalJSON.

func (NullNum) MarshalText

func (nn NullNum) MarshalText() ([]byte, error)

MarshalText returns an empty byte slice when !Valid, otherwise delegates to Num.MarshalText.

func (*NullNum) Scan

func (nn *NullNum) Scan(src any) error

Scan implements database/sql.Scanner. Handles nil → Valid=false.

func (NullNum) String

func (nn NullNum) String() string

String implements fmt.Stringer.

func (*NullNum) UnmarshalJSON

func (nn *NullNum) UnmarshalJSON(data []byte) error

UnmarshalJSON handles JSON null → Valid=false, otherwise delegates to Num.UnmarshalJSON.

func (*NullNum) UnmarshalText

func (nn *NullNum) UnmarshalText(data []byte) error

UnmarshalText handles empty input → Valid=false, otherwise delegates to Num.UnmarshalText.

func (NullNum) Value

func (nn NullNum) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer. Returns nil when !Valid.

type Num

type Num struct {
	Err error
	// contains filtered or unexported fields
}

Num is an immutable, error-carrying finite decimal. Its zero value is uninitialized; use Zero or a constructor for a valid numeric zero.

Example (ErrorChain)
package main

import (
	"fmt"

	"go.trippwill.dev/num"
)

func main() {
	exit := num.FromString("150.00")
	entry := num.FromString("100.00")
	qty := num.FromInt64(10)

	pnl := exit.Sub(entry).Mul(qty)
	if !pnl.Ok() {
		fmt.Println("error:", pnl.Err)
		return
	}
	fmt.Println(pnl)
}
Output:
500.00

func FromFloat64

func FromFloat64(v float64) Num

FromFloat64 interprets v using its shortest round-trip decimal spelling, rather than the exact binary fraction. NaN and infinities are invalid.

func FromInt64

func FromInt64(v int64) Num

FromInt64 constructs an exact integer at scale zero.

func FromString

func FromString(s string) Num

FromString constructs an exact decimal, retaining fractional trailing zeros. Malformed, nonfinite, or out-of-capacity inputs produce an error-state Num.

Example
package main

import (
	"fmt"

	"go.trippwill.dev/num"
)

func main() {
	n := num.FromString("123.45")
	fmt.Println(n)
}
Output:
123.45

func Zero

func Zero() Num

Zero constructs an initialized zero at scale zero.

func (Num) Abs

func (n Num) Abs() Num

Abs returns the absolute value, preserving scale and propagating errors.

func (Num) Add

func (n Num) Add(other Num) Num

Add returns the exact sum, retaining the greater operand scale.

Example
package main

import (
	"fmt"

	"go.trippwill.dev/num"
)

func main() {
	price := num.FromString("0.1")
	tax := num.FromString("0.2")
	total := price.Add(tax)
	fmt.Println(total)
}
Output:
0.3

func (Num) Cmp

func (n Num) Cmp(other Num) int

Cmp compares numerical values, independently of scale. Check both Ok first.

func (Num) Div

func (n Num) Div(other Num) Num

Div divides n by other using half-even rounding. Its precision is the greater of 34 and each operand's coefficient digits after removing trailing zeros. Repeating expansions succeed; a zero divisor or exceeded capacity does not.

func (Num) Equal

func (n Num) Equal(other Num) bool

Equal reports numeric equality. Check both Ok first.

func (Num) Format added in v0.3.0

func (n Num) Format(state fmt.State, verb rune)

Format implements fmt.Formatter. The f and F verbs round half-even to the requested number of fractional digits, defaulting to six, without changing n. They support width and the +, space, -, and 0 flags. The v and s verbs print the complete Num.String representation; q quotes it as a Go string. These text verbs support width and the - flag, and reject precision.

Precision is limited to 4096, width to 16384, and each formatted value to 16384 bytes. Unsupported formatting and invalid numeric states produce fmt diagnostics. Text verbs retain the error or uninitialized String marker.

func (Num) GreaterThan

func (n Num) GreaterThan(other Num) bool

GreaterThan reports numeric ordering. Check both Ok first.

func (Num) IsZero

func (n Num) IsZero() bool

IsZero reports whether n is valid and numerically zero.

func (Num) LessThan

func (n Num) LessThan(other Num) bool

LessThan reports numeric ordering. Check both Ok first.

func (Num) MarshalJSON

func (n Num) MarshalJSON() ([]byte, error)

MarshalJSON encodes n as an exact bare JSON number, retaining stored scale. No presentation formatting or binary floating-point conversion is involved.

Example
package main

import (
	"encoding/json"
	"fmt"

	"go.trippwill.dev/num"
)

func main() {
	n := num.FromString("42.50")
	data, _ := json.Marshal(n)
	fmt.Println(string(data))
}
Output:
42.50

func (Num) MarshalText

func (n Num) MarshalText() ([]byte, error)

MarshalText returns exact decimal text for text and XML encoders.

func (Num) Mul

func (n Num) Mul(other Num) Num

Mul returns the exact product, retaining the sum of operand scales.

func (Num) Neg

func (n Num) Neg() Num

Neg returns the negation, preserving scale and propagating errors.

func (Num) Ok

func (n Num) Ok() bool

Ok reports whether n is initialized and has no carried error.

func (Num) Quantize added in v0.3.0

func (n Num) Quantize(scale int) Num

Quantize rounds half-even or pads zeros to exactly scale fractional places. Scale must be between 0 and 4096 and the result must fit Num's capacity.

Example
package main

import (
	"fmt"

	"go.trippwill.dev/num"
)

func main() {
	price := num.FromString("1.235")
	fmt.Println(price.Quantize(2))
	fmt.Printf("display=%.2f exact=%s\n", price, price)
}
Output:
1.24
display=1.24 exact=1.235

func (*Num) Scan

func (n *Num) Scan(src any) error

Scan implements database/sql.Scanner. Accepted types are string, []byte, int64, uint64, float64, and float32. Floats use shortest decimal conversion; float32 first converts to float64, preserving the earlier driver contract.

func (Num) String

func (n Num) String() string

String returns exact plain decimal text, or an explicit error marker.

func (Num) Sub

func (n Num) Sub(other Num) Num

Sub returns the exact difference, retaining the greater operand scale.

func (*Num) UnmarshalJSON

func (n *Num) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts numeric tokens and quoted decimal strings. Invalid values clear the previous number and carry Err, allowing partial struct decode.

func (*Num) UnmarshalText

func (n *Num) UnmarshalText(data []byte) error

UnmarshalText parses exact decimal text, clearing stale state on failure.

func (Num) Value

func (n Num) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer using exact string-based output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL