liveBook · Manning

Subunit

As explained in Learn Go with Pocket-Sized Projects

A subunit is a fractional monetary unit used to represent a currency amount more precisely than the principal unit.

A subunit represents a monetary amount as an integer while precision records the power of 10 separating it from the principal unit. For example, 1.52 is stored as 152 subunits with precision 2, avoiding floating-point imprecision. section 6.2.4

Listing 6.6 decimal.go: Decimal struct implementation
// Decimal can represent a floating-point number with a fixed precision.
// example: 
// 1.52 = 152 * 10^(-2) will be stored as {152, 2} #1
type Decimal struct {
    // subunits is the amount of subunits. 
    // Multiply it by the precision to get the real value
    subunits int64 #2
    // Number of "subunits" in a unit, expressed as a power of 10.
    precision byte #3
}

Inspect the Decimal fields: subunits stores the integer quantity, while precision records how many decimal places reconstruct the value. section 6.2.4

A subunit-based representation supports:

  • Parsing decimal strings into an integer quantity and fractional precision. section 6.2.4
  • Removing trailing decimal zeroes by dividing subunits by 10 and reducing precision. section 6.2.4
  • Testing malformed, empty, and excessively large quantities with explicit errors. section 6.2.4

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains integer storage, power-of-ten precision, parsing, validation, testing, and simplification.
Examples
Uses 1.52 as 152 subunits, compares satoshi precision, and tests valid, invalid, empty, and oversized strings.
What you can do after
Build fixed-precision monetary values from strings and test their parsing and normalization.
How it connects
Connects subunits with Decimal, precision, parsing, custom errors, and floating-point imprecision.

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.