Floating-point error is the loss of accuracy caused by representing and calculating values with limited precision. Financial conversion makes this risk concrete: an exchange rate may carry several significant digits, while the converted amount must preserve the target currency’s precision. section 6.3.1
A practical strategy for avoiding unwanted error is to:
- Represent monetary quantities with a high-precision Decimal rather than relying on float32 or float64. section 6.3.1
- Multiply integer subunits and add precisions, then adjust the result to the target currency’s precision. section 6.3.1
- Test exact values, large numbers, very small rates, and rates that exceed supported magnitude. section 6.3.1
Currency conversion
Multiplying 20.00 by 4.0 produces 80.000 internally: subunits are multiplied and precisions are added. The result is then simplified and resized to match the target currency. section 6.3.1
Listing 6.18 convert.go: ExchangeRate type
// ExchangeRate represents a rate to convert from one currency to another. type ExchangeRate Decimal
Inspect the ExchangeRate type, which gives a currency-conversion rate an explicit high-precision representation. section 6.3.1
