Float data types in Go are designed for storing both positive and negative numbers that include a decimal point. These can represent numbers such as 12.75, -3.14, or 98765.4321.
In Go, float comes in two variations:
Type | Size | Range |
---|---|---|
float32 | 32 bits | -3.4e+38 to 3.4e+38 |
float64 | 64 bits | -1.7e+308 to +1.7e+308 |
Tip: If a specific float type is not defined, the default type in Go will be float64
.
The float32
Keyword
The float32
type is capable of storing numbers within a more restricted range compared to float64
.
Example: Declaring Variables of Type float32
Go
x
package main
import ("fmt")
func main() {
var ducati float32 = 150.45
var yamaha float32 = 3.4e+38
fmt.Printf("Type: %T, value: %v\n", ducati, ducati)
fmt.Printf("Type: %T, value: %v", yamaha, yamaha)
}
The float64
Keyword
The float64
type is capable of storing significantly larger numbers compared to float32
.
Example: Declaring Variables of Type float64
Go
package main
import ("fmt")
func main() {
var suzuki float64 = 1.7e+308
fmt.Printf("Type: %T, value: %v", suzuki, suzuki)
}
Choosing Between Float Types
Selecting the appropriate float type depends on the range and precision of the value that needs to be stored.
Example: Out-of-Range Error for float32
Go
package main
import ("fmt")
func main() {
var honda float32 = 3.4e+39
fmt.Println(honda)
}
Output:
Go
./prog.go:5:7: constant 3.4e+39 overflows float32