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
