← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 3 of 10

The math Package

The math package is Go's built-in calculator for things beyond basic + and -, like square roots, powers, and rounding.

Square Roots and Powers

math.Sqrt computes a square root, and math.Pow raises a base to an exponent -- both operate on and return float64, so integer inputs need explicit conversion.

Example: Square Roots and Powers

markup
package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Sqrt(16))
	fmt.Println(math.Pow(2, 10))
}

Absolute Value and Comparisons

math.Abs returns a value's non-negative magnitude, while math.Max and math.Min return the larger or smaller of exactly two float64 arguments.

Example: Absolute Value and Comparisons

markup
package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Abs(-7.5))
	fmt.Println(math.Max(3.2, 8.1))
	fmt.Println(math.Min(3.2, 8.1))
}

Rounding Numbers

math.Round rounds to the nearest whole number, math.Floor always rounds down, and math.Ceil always rounds up -- each returning a float64 representing that whole number.

Example: Rounding Numbers

markup
package main

import (
	"fmt"
	"math"
)

func main() {
	n := 4.6
	fmt.Println(math.Round(n))
	fmt.Println(math.Floor(n))
	fmt.Println(math.Ceil(n))
}
Common Mistakes
  1. Forgetting math functions work on float64, requiring explicit conversion when starting with an int.
  2. Assuming math.Max/Min work on slices directly -- they only compare two float64 values at a time.
  3. Not checking for math.IsNaN or math.IsInf when a computation (like dividing by zero as a float) could produce a non-numeric result.
Chapter Summary
  • The math package works with float64 values, so ints must be explicitly converted first.
  • math.Sqrt, math.Pow, and math.Abs handle common numeric operations.
  • math.Max and math.Min compare exactly two float64 values at a time.
  • math.Round, Floor, and Ceil control how a float is rounded to a whole number.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.