Go Float Data Types #
Float data types are used to store positive and negative numbers with a decimal point, such as 35.3, -2.34, or 3597.34987.
Go has two float data types:
| Type | Size | Range |
|---|---|---|
| float32 | 32 bits | -3.4e+38 to 3.4e+38 |
| float64 | 64 bits | -1.7e+308 to +1.7e+308 |
Tip: The default float type in Go is
float64. If you do not specify a type, it will default tofloat64.
The float32 Keyword #
float32 stores decimal numbers with single precision.
package main
import ("fmt")
func main() {
var x float32 = 123.78
var y float32 = 3.4e+38
fmt.Printf("Type: %T, value: %v\n", x, x)
fmt.Printf("Type: %T, value: %v\n", y, y)
}The float64 Keyword #
float64 stores decimal numbers with double precision and can hold larger numbers than float32.
package main
import ("fmt")
func main() {
var x float64 = 1.7e+308
fmt.Printf("Type: %T, value: %v\n", x, x)
}Choosing the Right Float Type #
The float type you choose depends on the range of values your variable needs to store. Using a type with insufficient range will cause an error.
package main
import ("fmt")
func main() {
var x float32 = 3.4e+39
fmt.Println(x)
}Result:
./prog.go:5:7: constant 3.4e+39 overflows float32Always choose a float type that can safely hold the expected value range.