Numbers in Go
Master numeric operations in Go: creation, math utilities, rounding, random numbers, powers, roots, and conversions between numbers and strings.
Creating Numbers
Go has several numeric types: int, int64, uint, float32, float64, and others. There is no single "Number" type; you choose the type that fits your data. For most general use, int and float64 are common.
1. Integers and Floats
Use int for integers and float64 for decimal numbers.
2. Byte (1-Byte Unsigned Integer)
The type byte is an alias for uint8: values from 0 to 255.
Finding Min and Max
Go 1.21+ has built-in min and max functions that work with ordered types (integers, floats, strings). For two values, use min(a,b) or max(a,b). For more, chain them or use a loop.
1. Finding Minimum
Use the built-in min() function (Go 1.21+).
2. Finding Maximum
Use the built-in max() function (Go 1.21+).
Rounding Numbers
Use math.Round for "round to nearest integer". For N decimal places, scale by 10^N, round, then scale back, or use formatting and parsing.
1. Rounding to Integer
Use math.Round() from the math package. It returns a float64.
2. Rounding to N Decimal Places
Scale by 10^N, round, then divide by 10^N.
Floor and Ceiling
math.Floor returns the largest integer less than or equal to the value. math.Ceil returns the smallest integer greater than or equal. Both take and return float64.
1. Floor of a Number
Use math.Floor().
2. Ceiling of a Number
Use math.Ceil().
Random Numbers
The math/rand package provides rand.Float64() for [0, 1) and rand.Intn(n) for [0, n). From Go 1.20 onward, the default generator is seeded automatically. For random integers in [a, b] inclusive, use rand.Intn(b-a+1)+a.
1. Random Float from 0 to 1
rand.Float64() returns a float in [0, 1) — includes 0, excludes 1.
2. Random Integer from a to b (Inclusive)
Use variables a and b, then rand.Intn(b-a+1)+a so both bounds are inclusive.
Powers and Roots
Use math.Pow(x, y) for x^y. For an integer power of an integer, you can also use a loop or math.Pow. The nth root of x is math.Pow(x, 1/n) (use 1.0/n for float division).
1. Finding a^b
Use math.Pow(a, b). Both arguments and the result are float64.
2. Finding Nth Root
The nth root of x is x^(1/n). Use 1.0/n so the exponent is float.
Number ↔ String Conversion
Use strconv.Itoa and strconv.FormatFloat for number → string. Use strconv.Atoi and strconv.ParseFloat for string → number. Always check the error return for parsing.
1. Converting Number to String
Use strconv.Itoa for int, strconv.FormatFloat for float64.
2. Converting String to Number
Use strconv.Atoi for int and strconv.ParseFloat for float. Check the error.
Validating Numbers
Go does not have NaN for integers. For string-to-number validation, call strconv.Atoi or strconv.ParseFloat and check if err != nil. Invalid input returns an error instead of a special value.
1. Checking if a String is a Valid Number
Attempt to parse and check the error. Invalid strings return a non-nil error.