Numbers in C#
Use int, long, float, double, decimal for financial math, Math class utilities, random numbers, parsing, and number formatting.
Creating Numbers
1. Creating a Normal Number
Use `int` for whole numbers and `double` for decimals. C# infers `int` and `double` by default.
2. Creating a 1-Byte Numeric Variable
`byte` holds values from 0 to 255 — useful for raw binary data, image pixels, or network bytes.
Finding Min and Max
1. Finding Minimum
`Math.Min(a, b)` returns the smaller of two values.
2. Finding Maximum
`Math.Max(a, b)` returns the larger of two values.
Rounding Numbers
1. Rounding to Integer
`Math.Round()` rounds to the nearest integer. By default it uses "banker's rounding" (rounds .5 to the nearest even number).
2. Rounding to N Decimal Places
`Math.Round(value, digits)` rounds to a specific number of decimal places.
Floor and Ceiling
1. Floor of a Number
`Math.Floor()` always rounds down to the nearest integer — towards negative infinity.
2. Ceiling of a Number
`Math.Ceiling()` always rounds up to the nearest integer — towards positive infinity.
Random Numbers
1. Random Number from 0 to 1
`Random.NextDouble()` returns a random `double` between 0.0 (inclusive) and 1.0 (exclusive).
2. Random Integer from a to b
`Random.Next(min, max)` returns a random integer where `min` is inclusive and `max` is exclusive.
Powers and Roots
1. Finding a^b (Power)
`Math.Pow(base, exponent)` raises a number to a power.
2. Square Root and Nth Root
Use `Math.Sqrt()` for square root and `Math.Pow(x, 1.0/n)` for the nth root.
Number ↔ String Conversion
1. Converting Number to String
Use `.ToString()` or string interpolation to convert a number to a string.
2. Converting String to Number
Use `int.Parse()`, `double.Parse()`, or the safe `TryParse()` variants.
Overflow & Decimal Precision
1. Integer Overflow
When an integer exceeds its max value, it wraps around silently. Use `checked {}` to throw an exception instead.
2. decimal for Financial Math
`double` has floating-point rounding errors. `decimal` is exact — always use it for money.