Go Float Data Type

Gayathri. B

 Go Float Data Types

  • In Go, float data types are used to store numbers that include a decimal point, such as 35.3, -2.34, or 3597.34987. These types can represent both positive and negative real numbers.
  • Go provides two floating-point types:

Tip:If you don't explicitly specify a type, Go defaults to float64.

The float32 Keyword in Go

  • The float32 type is used to store decimal numbers (both positive and negative) with single precision. It occupies 32 bits of memory and can represent values approximately between ±3.4e+38.

Example:

  • The following example demonstrates how to declare and use variables of type float32:
package main
import "fmt"
func main() {
  var x float32 = 123.78         // standard decimal number
  var y float32 = 3.4e+38        // scientific notation
  fmt.Printf("Type: %T, value: %v\n", x, x)
  fmt.Printf("Type: %T, value: %v", y, y)
}

Output:

Type: float32, value: 123.78  
Type: float32, value: 3.4e+38
Note: Use float32 when memory efficiency is important and high precision is not required.

The float64 Keyword

  • The float64 data type in Go is used to store floating-point numbers with double precision. It can hold a much larger and more precise range of values compared to float32.

Example:

The following example demonstrates how to declare and use a float64 variable:
package main
import ("fmt")
func main() {
  var x float64 = 1.7e+308
  fmt.Printf("Type: %T, value: %v", x, x)
}

Choosing the Right Float Type

  • When selecting a floating-point type in Go, it’s important to consider the size and range of the value you want to store.

Example:

  • The following program will produce an error because the value 3.4e+39 exceeds the maximum limit for the float32 type:

package main

import "fmt"

func main() {

  var x float32 = 3.4e+39

  fmt.Println(x)

}

Output:

./prog.go:5:7: constant 3.4e+39 overflows float32

Explanation:

  • float32 can store values roughly in the range of ±3.4e+38.
  • Attempting to assign a larger value will cause a compile-time overflow error.
  • To store larger floating-point numbers, use float64 instead.









Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send