liveBook · Manning

Floating-point error

As explained in Learn Go with Pocket-Sized Projects

A floating-point error is an inaccuracy caused by the finite binary representation and arithmetic of floating-point numbers.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains representation, multiplication, precision adjustment, and boundary tests, but does not develop floating-point internals.
Examples
Uses exchange-rate multiplication, target-currency rounding, very small rates, large amounts, and excessive rates.
What it assumes
Assumes familiarity with numeric types and introduces Decimal-based subunit and precision handling for conversion.
What you can do after
Apply via a Decimal representation and precision-aware tests when exact monetary results matter.
How it connects
Connects floating-point error with Decimal, exchange rates, monetary amounts, and currency precision.

Related concepts

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.