liveBook · Manning

Float64

As explained in 100 Go Mistakes and How to Avoid Them

float64 is Go's 64-bit floating-point type with an 11-bit exponent, a 52-bit mantissa, and a sign bit.

float64 is Go’s double-precision floating-point type. It stores a finite approximation of real values using 64 bits: 11 exponent bits, 52 mantissa bits, and one sign bit. Floating-point arithmetic therefore may lose precision. section 3.3

Mistake: expecting exact decimal arithmetic

Multiplying 1.0001 by itself may print 1.0002 instead of the expected 1.00020001. The stored value cannot represent every real number exactly, so arithmetic operates on approximations. section 3.3

var n float32 = 1.0001
fmt.Println(n * n)

Running a floating-point multiplication exposes the difference between expected decimal arithmetic and the value produced by approximation. section 3.3

Account for these behaviors when using float64:

  • Changing operation order can change accumulated error: adding 1.0001 repeatedly before adding 10,000 produces different results from adding 10,000 first. section 3.3
  • Algebraically equivalent expressions can differ numerically: a × (b + c) and a × b + a × c produce slightly different outputs. section 3.3
  • Floating-point values can represent positive infinity, negative infinity, and NaN through operations such as division by zero. section 3.3

Mistake: assuming decoded JSON numbers are integers

Unmarshaling JSON into map[string]any converts numeric values to float64, even when the JSON value has no decimal. Code that assumes m["id"] is an integer can therefore make an incorrect type assertion and cause problems. section 10.3.3

fmt.Printf("%T\n", m["id"])
float64

Printing the dynamic type of a decoded numeric map value reveals float64 directly. section 10.3.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines the IEEE-754 bit layout and demonstrates rounding, accumulation order, expression order, special values, and JSON conversion.
Examples
Uses multiplication, repeated addition, reassociated expressions, special-value divisions, and decoded JSON identifiers.
What it assumes
Assumes basic Go values and arithmetic while introducing floating-point approximation, representation, and map-based JSON decoding.
What you can do after
Diagnose unexpected rounding, accumulation differences, special values, and numeric type assertions in decoded maps.
How it connects
Connects floating-point arithmetic with IEEE-754, JSON unmarshaling, dynamic maps, type conversions, infinity, and NaN.

Also explained in

Compare how 7 books explain float64 →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.