decint

decint provides utility functions to parse and represent decimal values as fixed-point integers with a defined precision.

Part of nurago, a collection of independent Go packages for backend services.

import "github.com/tecnickcom/nurago/pkg/decint"

Package decint provides utility functions to parse and represent decimal values as fixed-point integers with a defined precision.

Values with at most six decimal places are stored as integers (scaled by 1e6) to preserve deterministic behavior in comparisons, serialization, and transport.

The package provides bidirectional conversion between float64/string and scaled int64 or uint64, fixed six-decimal output formatting, explicit parse errors for invalid numeric strings, safe range constants (MaxInt and MaxFloat) for boundary checks, and unsigned conversion helpers that clamp non-positive values to zero.

Implementation note:

  • float-to-integer conversion scales by 1e6 and rounds to the nearest integer (half away from zero), so extra fractional digits beyond the supported precision are rounded rather than truncated.

Safe range:

  • Values are safe up to MaxFloat = 2^33 = 8_589_934_592 with six exact decimal places. This is the largest magnitude at which a float64 still resolves a 1e-6 step (its ULP stays below 1e-6); beyond it the sixth decimal digit is no longer representable, so it is excluded from the safe range rather than rounded.

When To Use

  • Money or quantities must not accumulate binary floating-point error.
  • Values are stored as integers and formatted for display with a fixed number of decimals.

Example

v := decint.FloatToInt(123.456)

fmt.Println(v)

// Output:
// 123456000

Full source is in example_int64_test.go. More runnable examples are on pkg.go.dev.

Dependencies

This package reaches no external module: it uses only the Go standard library.