Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 182 ยท Standard Library

Math, BigInteger and Random

Learn the C# Math class, rounding modes, BigInteger, Complex, Int128, seeded Random, secure random numbers and safe number parsing, with runnable examples.

Almost every program needs some arithmetic beyond + and -: square roots, powers, rounding a price, picking a random item, multiplying numbers that no longer fit in a long. .NET puts these tools in a handful of places: the static Math and MathF classes, System.Numerics for big and complex numbers, Random for pseudo-random values and RandomNumberGenerator for cryptographic ones.

This lesson walks through them in the order you will need them, and points out the traps: Math.Round does not round the way school taught you, floating-point results are approximate, Random is not secure, and parsing numbers needs a culture.

For the basics of integer and floating-point types see Integers and Floating-Point Numbers. Everything below builds on them.

The Math class

Math is a static class with double methods (and many generic or decimal/int overloads). It also holds two constants, Math.PI and Math.E:

C# Everyday Math methods

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 Console.ReadLine()), it gets the next line from this box.

Math.Floor, Ceiling and Truncate differ only for negative numbers: -2.5 floors to -3, ceils to -2 and truncates to -2. For the length of a hypotenuse there is no Math.Hypot; write Math.Sqrt(a * a + b * b) or use double.Hypot(a, b) from the next example.

Trigonometry and angles

Trigonometric functions use radians, not degrees. A half turn is Math.PI radians. Convert with degrees * Math.PI / 180:

C# Trigonometry in radians

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 Console.ReadLine()), it gets the next line from this box.

Math.Sin(Radians(30)) prints something like 0.49999999999999994, not exactly 0.5: computers store most fractions in binary and only approximately. Round for display, never compare floating-point results with ==; use a tolerance such as Math.Abs(a - b) < 1e-9.

Rounding

Math.Round uses banker's rounding by default (MidpointRounding.ToEven): a value exactly halfway goes to the nearest even number. That avoids a statistical bias when you round many values, but it surprises people:

C# Rounding modes

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 Console.ReadLine()), it gets the next line from this box.

Two lessons here. First, pick the mode that matches your business rule: money rounding in many countries means AwayFromZero. Second, the double literal 1.005 is really stored as 1.00499999999999989..., so it is not a tie at all and rounds down to 1, while the decimal 1.005m is an exact tie. For money use decimal, which stores base-10 digits exactly. (Math.Round accepts 0 to 15 digits for double and 0 to 28 for decimal; negative digits throw ArgumentOutOfRangeException, so divide, round and multiply instead.)

Integer division and remainders

With integers, / truncates and % gives the remainder (with the sign of the left operand). Math.DivRem returns both, and Math.Floor style division needs care with negatives:

C# Division, remainder and overflow

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 Console.ReadLine()), it gets the next line from this box.

Overflow wraps around by default in ordinary code. If silent wrapping would be a bug (counting money, sizes, indexes), wrap the risky expression in checked(...) or use Math.BigMul/long for the intermediate result.

decimal for money

decimal has 28 to 29 significant digits and works in base 10. It is slower than double but exact for amounts like 0.10:

C# double versus decimal

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 Console.ReadLine()), it gets the next line from this box.

BigInteger: numbers without limits

System.Numerics.BigInteger grows as needed, limited only by memory. Use it for factorials, huge Fibonacci numbers, exact combinatorics and cryptography-style math:

C# BigInteger

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 Console.ReadLine()), it gets the next line from this box.

BigInteger values are immutable and heap-allocated, so loops that multiply thousands of times allocate a lot. It is perfect for correctness and unsuitable for tight numeric loops. A BigInteger converts to long or int with an explicit cast that throws OverflowException if the value does not fit.

Int128 and UInt128

If you only need a little more room than long, Int128 and UInt128 (since .NET 7) are fixed-size 128-bit integers. They overflow like other integers but hold up to about 1.7 times 10 to the 38th:

C# Int128

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 Console.ReadLine()), it gets the next line from this box.

Complex numbers

System.Numerics.Complex stores a real and an imaginary part. Operators work as you would expect:

C# Complex numbers

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 Console.ReadLine()), it gets the next line from this box.

Random numbers

Random makes pseudo-random numbers from a seed. The same seed gives the same sequence on the same runtime, which is perfect for repeatable simulations and tests. Without a seed the start is unpredictable. Random.Shared (since .NET 6) is a ready-made, thread-safe instance for everyday use:

C# Seeded Random

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 Console.ReadLine()), it gets the next line from this box.

The printed values depend on the runtime's algorithm; they are repeatable for a given seed on this .NET version but are not guaranteed to be identical across future versions. Never write a test that hardcodes the numbers unless you pin the runtime.

Fair ranges

rng.Next(n) is uniform. A common bug is rng.Next() % n, which is slightly biased, and rng.Next(0, 6) forgetting that the upper bound is exclusive: it never returns 6.

Secure random numbers

Random is predictable if someone learns its state, so it must not be used for passwords, tokens, session ids or keys. System.Security.Cryptography.RandomNumberGenerator draws from the operating system's cryptographic source:

C# RandomNumberGenerator

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 Console.ReadLine()), it gets the next line from this box.

Output of this snippet is intentionally printed as lengths because the values are, by design, different every time. GetString exists since .NET 8 and avoids the bias of hand-written % alphabet.Length code.

Do not use new Random() or Random.Shared to generate anything an attacker must not guess. Use RandomNumberGenerator.

Parsing numbers

User input is text. int.Parse throws on bad input; int.TryParse returns a bool. Numbers also depend on culture: a decimal separator may be . or ,, and thousands separators vary. Pass a culture and the styles you accept:

C# Safe number parsing

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 Console.ReadLine()), it gets the next line from this box.

Notes:

  • NumberStyles.Integer allows leading and trailing spaces and a sign but no thousands separator, so "1,234" fails. Use NumberStyles.Number or NumberStyles.AllowThousands to accept it.
  • Parsing a double from "1e3" needs NumberStyles.Float, which double.Parse uses by default.
  • For text shown to the user, parse with the user's culture; for files and network data, always CultureInfo.InvariantCulture.

Generic math

Since .NET 7 numeric types implement interfaces such as INumber<T>, so you can write one method that works for int, double, decimal and BigInteger. That feature has its own lesson: Generic Math.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Math.Round(2.5) return?

    The default is MidpointRounding.ToEven (banker's rounding), so 2.5 becomes 2 and 3.5 becomes 4. Pass MidpointRounding.AwayFromZero to get 3.
  2. 2. Which type should you use to store a price like 19.99?

    decimal stores base-10 digits, so values like 0.1 are exact. float and double are binary and only approximate.
  3. 3. Which API is appropriate for generating a password-reset token?

    Only RandomNumberGenerator is cryptographically secure. Random can be predicted.
  4. 4. What is new Random(7).Next(1, 7) able to return?

    The upper bound of Next(min, max) is exclusive, so the result is always at least 1 and below 7.
  5. 5. Why does int.TryParse("1,234", out var n) return false?

    int.TryParse uses NumberStyles.Integer, which excludes thousands separators. Use NumberStyles.Number to allow them.

Summary

  • Math offers powers, roots, logs, trigonometry (in radians), Clamp, DivRem and rounding helpers.
  • Math.Round rounds halves to even by default; pass MidpointRounding.AwayFromZero when your rules say so.
  • Use decimal for money, never double; compare floating-point values with a tolerance.
  • Integers wrap on overflow unless you use checked.
  • BigInteger has no size limit, Int128 is a fixed 128 bits, and Complex models complex numbers.
  • Random(seed) is repeatable; Random.Shared is the default; RandomNumberGenerator is for security.
  • Parse with TryParse, explicit NumberStyles and a culture.

Next: Files, Paths and Directories