Golang Floating Point Numbers

Golang Floating Point Numbers

Floating point numbers are numbers than can have a fractional (decimal) value. Floats in Golang are always signed and can therefore take positive or negative values.

There are only two types of floats in Go, float32 and float64. These are shown in the table below:

Float TypeDescriptionRange
float3232-bit float; can be positive or negative-3.4e+38 to +3.4e+38
float6464-bit float; can be positive or negative-1.7e+308 to +1.7e+308

Note that the default type of float is float64. If a float type isn’t specified, then float64 will be assigned.

Working With Floats in Go

As with integers, one of the most common ways of working with floats is by using them in variables. The following example shows how to declare both types of floats, as well as using the default float type (which is float64):

package main

import (
	"fmt"
)

func main() {

	var num1 = 42.1         // Defaults to float64 type
	var num2 float32 = 13.3 // float32 type
	var num3 float64 = 26.4 // float64 type

	fmt.Println(num1)
	fmt.Println(num2)
	fmt.Println(num3)
	fmt.Println(num1 + num3)
}

Output:

42.1
13.3
26.4
68.5

Note that we were able to add ‘num1 + num3’ because both variables have a type of ‘float64’.