Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 147 ยท Variables and Types

Numbers and Math

Work with numbers in Go - integer division, overflow, float precision, NaN and Inf, the math package, math/big, math/bits and parsing numbers with strconv.

Computing with numbers is something nearly every program does, and Go gives you a clear, predictable toolkit for it. Integer math is exact and wraps around on overflow, floating-point math follows the IEEE 754 standard like in every mainstream language, and the standard library adds the math package for the usual functions, math/big for numbers of any size, and math/bits for working with individual bits.

This lesson shows how the arithmetic operators behave for integers and floats, how to avoid typical surprises (integer division, rounding errors, NaN), how to use math, math/big and math/bits, and how to turn text into numbers. It builds on the basic types lesson; random numbers have their own lesson in the standard library chapter (math and random).

Integer arithmetic

The operators +, -, *, / and % work on integers as you would expect, with two details worth remembering:

  • / on two integers is integer division: the fractional part is thrown away (rounded toward zero).
  • % is the remainder, and its sign follows the dividend (the left operand).
Go Integer division and remainder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

If you want a result that is never negative (for example to wrap an index around a list), adjust it yourself: ((i % n) + n) % n.

Dividing an integer by zero stops the program with a panic at run time (and is a compile error if the zero is a constant):

Go Division by zero (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output shows before, then a panic that starts with panic: runtime error: integer divide by zero and a goroutine 1 [running]: trace pointing at main.go:8. The program exits with code 2 and never prints "after". Floating-point division by zero doesn't panic; it gives infinity, as shown below.

Shorthand and the increment statements

x += 5, x -= 5, x *= 5, x /= 5 and x %= 5 combine an operation with assignment. x++ and x-- increase or decrease by one. In Go, ++ and -- are statements, not expressions, so y = x++ and ++x are not valid. Operators lists them all.

Overflow

Integers have a fixed size and wrap around at the ends of their range (see basic types). Because nothing warns you, check calculations that might get large. One simple approach is to do the math in a wider type and compare against the limits:

Go Detecting overflow before it happens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

20! fits in an int64 (it is about 2.4 ร— 10^18), but 21! doesn't, so from 21 on the results are wrong: 21! comes out as a negative number, and 25! is a plausible-looking but incorrect value. Use math/big, shown below, whenever values can grow without a known limit.

Floating-point numbers

float64 is the type for fractional numbers. It stores a binary approximation with 53 significant bits, which means most decimal fractions are stored inexactly. A few rules keep you out of trouble:

  1. Don't compare results with ==. Compare with a small tolerance instead.
  2. Don't use floats for money. Keep integer cents, or use a decimal library.
  3. When adding many numbers of very different sizes, expect small rounding errors.
Go Comparing floats with a tolerance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

1e16 + 1 == 1e16 is true because a float64 can't represent that last unit at such a size. Floating-point precision is a property of the representation, not a Go flaw.

Infinity and NaN

Floating-point division doesn't panic. Dividing a non-zero number by zero gives infinity, and operations without a sensible answer give NaN ("not a number"). NaN has a notorious property: it is not equal to anything, not even itself.

Go Inf and NaN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Always test for NaN with math.IsNaN(x), never with x == math.NaN(). If a NaN gets into a calculation, it spreads to every result that depends on it. A NaN also can't be encoded as JSON; marshaling one returns an error.

The math package

The math package has the functions you would expect, all working on float64:

Go Useful functions from math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Note that math.Round rounds halves away from zero, while RoundToEven uses banker's rounding. To round to a number of decimals, multiply, round and divide: math.Round(x*100) / 100. For display, format with %.2f instead.

For integers there is no math.Abs or math.Max. Since Go 1.21 you can use the built-in min and max functions on any ordered type, and the cmp and slices packages cover the rest. For the absolute value of an integer, write a three-line helper or convert carefully:

Go Built-in min and max, and an integer abs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

More functions: math and math/cmplx

Beyond the everyday functions, math has a handful of special-purpose ones that are handy once you need them:

Go Less common math functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Expm1 and Log1p exist because math.Exp(x)-1 subtracts two nearly equal numbers and throws away most of the significant digits when x is tiny; the dedicated functions keep them. Float64bits exposes the bit pattern (0x3ff0000000000000 for 1.0), and Float64frombits goes back. Note that the constant -0.0 in Go source is just 0, so Signbit reports false for it; only a computed negative zero, here Copysign(0, -1), has the sign bit set.

Complex numbers

Go has built-in complex types, complex64 and complex128. Write them with complex(re, im) or an imaginary literal like 3i, take them apart with real and imag, and use the package math/cmplx for the functions:

Go complex128 and math/cmplx

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

cmplx.Abs is the magnitude (5 for 3+4i), Conj flips the sign of the imaginary part, and Polar returns the magnitude and the angle in radians. Complex values print as (3+4i). Because they are floating-point, Euler's identity gives about 1.2e-16 instead of exactly zero.

Big numbers with math/big

When a value can exceed 64 bits, or you need exact decimal fractions, use math/big. It has three types: big.Int (whole numbers of any size), big.Float (floating point with chosen precision) and big.Rat (exact fractions). They are used through methods on pointers; each method stores the result in its receiver:

Go Exact big integers, rationals and floats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because the methods write into their receiver, f.Mul(f, x) multiplies in place and avoids allocating a new number. Operators such as + and * do not work on big numbers; you must call methods. big.Int also has Mod, Div, GCD, ProbablyPrime and ModInverse, which are the building blocks of cryptography.

Working with bits: math/bits

When you do low-level work such as bitmaps, hashing or compression, the math/bits package provides fast, portable operations on unsigned integers, many of them mapped straight to CPU instructions:

Go Counting and rotating bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

bits.Add64 and bits.Mul64 return the carry or the high half of the result, so you can detect and handle overflow exactly. There are 8, 16, 32 and 64-bit versions of most functions, plus unsized ones for uint.

Parsing and formatting numbers

User input and files give you text, and the strconv package turns it into numbers. Always check the error, because users type surprising things:

Go Parsing numbers from strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Atoi ("ASCII to integer") and Itoa are the everyday pair. ParseInt takes a base (0 means "detect from the prefix") and a bit size, and rejects values that don't fit. Reading input uses these functions with real input, and the type conversion lesson compares them with string(n), which does not do what you might expect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fmt.Println(7 / 2, 7 % 2, -7 / 2) print?

    Integer division truncates toward zero, so 7/2 is 3 and -7/2 is -3. The remainder 7 % 2 is 1.
  2. 2. What happens when an int variable is divided by an int variable whose value is 0?

    Integer division by zero is a run-time panic. Only floating-point division gives Inf or NaN.
  3. 3. What does math.NaN() == math.NaN() evaluate to?

    NaN is not equal to anything, including itself. Use math.IsNaN to test for it.
  4. 4. Why does 0.1 + 0.2 == 0.3 print false for float64 variables?

    The values are stored as binary approximations, so the sum is 0.30000000000000004, which differs from the closest double to 0.3.
  5. 5. How do you add two *big.Int values a and b into a new number?

    big.Int values are used through methods. new(big.Int).Add(a, b) stores the sum in a fresh big.Int.

Summary

  • Integer / truncates toward zero and % takes the sign of the left operand. Integer division by zero panics; float division by zero gives Inf or NaN.
  • Integer overflow wraps silently, so widen the type, check ranges, or use math/bits (Add64, Mul64) or math/big when values can grow.
  • Floats are binary approximations: compare with a tolerance, test NaN with math.IsNaN, and keep money in integer cents.
  • The math package covers roots, powers, rounding (Round, Floor, Ceil, Trunc), trigonometry and logarithms; use the built-in min and max (Go 1.21) for ordered values.
  • math/big gives Int, Rat and Float of any size or exactness, used through methods on pointers.
  • strconv parses and formats numbers and returns an error for bad input.

Next: Strings, Bytes and Runes