Numbers & Math (Integers, Floats, Math Package) - Go Tutorial for Beginners #4
Video: Numbers & Math (Integers, Floats, Math Package) - Go Tutorial for Beginners #4 by Taught by Celeste AI - AI Coding Coach
Watch full page →Numbers & Math in Go: Integers, Floats, and the Math Package
In Go, working with numbers involves understanding integer and floating-point types, arithmetic operations, and the math package's utilities. This guide covers integer arithmetic, float precision, division differences, math functions like square root and power, and how to convert between numeric types safely.
Code
package main
import (
"fmt"
"math"
)
func main() {
// Integer arithmetic
a, b := 17, 5
fmt.Println("a + b =", a+b) // Addition: 22
fmt.Println("a - b =", a-b) // Subtraction: 12
fmt.Println("a * b =", a*b) // Multiplication: 85
fmt.Println("a / b =", a/b) // Integer division: 3 (decimal discarded)
fmt.Println("a % b =", a%b) // Modulo (remainder): 2
// Floating-point numbers
var f1 float64 = 17.0
var f2 float64 = 5.0
fmt.Printf("f1 / f2 = %.2f\n", f1/f2) // Float division: 3.40
// Float32 uses less memory but less precision
var f3 float32 = 3.14159
fmt.Printf("Float32 value: %.2f\n", f3)
// Using the math package
fmt.Println("Pi:", math.Pi) // Constant Pi
fmt.Println("Sqrt(16):", math.Sqrt(16)) // Square root: 4
fmt.Println("Pow(2, 3):", math.Pow(2, 3)) // Power: 8
fmt.Println("Round(3.7):", math.Round(3.7)) // Round to nearest: 4
fmt.Println("Floor(3.7):", math.Floor(3.7)) // Floor (down): 3
fmt.Println("Ceil(3.3):", math.Ceil(3.3)) // Ceil (up): 4
// Type conversions
var x int = 10
var y float64 = float64(x) // int to float64
fmt.Println("Converted int to float64:", y)
var z float64 = 3.99
var w int = int(z) // float64 to int (truncates decimal)
fmt.Println("Converted float64 to int:", w)
}
Key Points
- Integer division truncates the decimal part, while float division retains decimals.
- The math package offers useful constants and functions like Pi, Sqrt, Pow, Round, Floor, and Ceil.
- Floats come in float32 and float64; float64 is the default for precision.
- Modulo (%) returns the remainder of integer division.
- Explicit type conversions are required between numeric types to avoid precision loss or errors.