I'm currently available for contract work & technical writing opportunities. Hire me

How to divide numbers in Go correctly

In this post, you will learn how to avoid weird results when performing integer division in Go

The result of performing integer division in Go can be surprising if you’re new to the language. For example, 20 ÷ 8 gives 2 instead of 2.5.

func main() {
	fmt.Println(20 / 8) // 2
}

Both numbers are treated as untyped integer constants and operations on untyped constants of the same type yields a result of the same kind. This is why we get 2 as the result of the operation above.

For operations between untyped constants of different types, the result would be in the kind that appears later in this list: integer, rune, floating-point, complex. For example, an operation between an untyped floating-point constant and an untyped integer constant will yield a floating-point constant.

func main() {
	fmt.Println(20.0 / 8) // 2.5
	fmt.Println(20 / 8.0) // 2.5
}

When dividing variables, ensure both are converted to the float64 type first.

func main() {
	a := 20
	b := 3
	fmt.Println(float64(a) / float64(b)) // 6.666666666666667
	// Don't do this
	fmt.Println(float64(a / b)) // 6
}

Thanks for reading, and happy coding!