Choose floating-point and complex types in Go
Fractional measurements
Use floating-point types for measurements such as distance or temperature that can have fractional parts. Go provides IEEE 754 float32 and float64, with 32 and 64 bits respectively. float64 offers more precision and range and is the ordinary default for fractional literals. Neither represents every decimal fraction exactly. For exact monetary amounts, an integer in the smallest currency unit can be appropriate.
package main
import "fmt"
func main() { var distance float64 = 12.5 var factor float32 = 1.25 fmt.Println(distance, factor)}The output is 12.5 1.25. These particular fractions are exactly representable in binary. Do not assume the same for 0.1. Rounding and comparison are studied in the next chapter.
Complex quantities
package main
import "fmt"
func main() { var signal complex128 = 3 + 4i fmt.Println(real(signal), imag(signal))}The output is 3 4. A complex number has real and imaginary parts. complex64 uses two float32 components; complex128 uses two float64 components. The built-ins real and imag extract the two components, and complex(r, i) constructs a complex value from two compatible floating-point components (or untyped constants). Complex values are useful in signal processing; most ordinary measurements only need a float.
Try it locally
Declare a float64 length of 7.5 and a complex128 sample of 2 + 5i. Print the length and the imaginary part. Expected: 7.5 5. Hint: use imag on sample.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and Basic Types 03: Choose floating-point and complex types in Go
Check the lesson objective before moving on.
Which type has more precision than float32?
What is imag(3 + 4i)?