Go Float Data Types
Float types are for numbers that have a decimal point, whether positive or negative, such as 35.3, -2.34 or 3597.34987.
You can pick between two of them:
float32- takes 32 bits and reaches from -3.4e+38 to 3.4e+38float64- takes 64 bits and reaches from -1.7e+308 to 1.7e+308
Note: When no type is given, Go uses float64.
The float32 Keyword
Example
Both variables below are declared as float32. The second one sits close to the top of the range:
Prompt
Declare two float32 variables: one with a decimal value and one with scientific notation. Print their type and value.
Output: Go program and captured output
main.go
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
Choose float64 when you need to cover a wider span of numbers, since its range is far greater than that of float32.
Example
The value here, 1.7e+308, would never fit in a float32, so the variable is declared as float64:
Prompt
Declare a float64 variable with a large value. Print its type and value.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
var x float64 = 1.7e+308
fmt.Printf("Type: %T, value: %v\n", x, x)
}
Which Float Type to Use?
As with integers, the values you plan to store should drive the decision.
Go reports an error if a value does not fit in the range of its declared type. A value of 3.4e+39, for instance, is too large for float32.