Math Functions
Master VB 2026's built-in Math class — absolute value, square root, power, logarithms, rounding (Floor, Ceiling, Round, Truncate), min/max, random numbers, and practical applications in finance, physics, and data processing.
System.Math class, aliased as just Math in VB 2026. Important constants: Math.PI ≈ 3.14159 and Math.E ≈ 2.71828. The four rounding functions have critically different behaviour: Math.Floor always rounds down, Math.Ceiling always rounds up, Math.Truncate always rounds toward zero, and Math.Round rounds to nearest even (banker's rounding) by default. Use Math.Round(x, digits, MidpointRounding.AwayFromZero) for the conventional "round half up" most people expect.
18.1 Abs, Sqrt, and Pow
' Math.Abs -- absolute value (removes sign) Dim temperature = -12.5 lblAbs.Text = $"Temperature deviation: {Math.Abs(temperature)} degrees" ' 12.5 Dim balance = -350.0 lblBalance.Text = If(balance < 0, $"Overdrawn: RM {Math.Abs(balance):F2}", $"Balance: RM {balance:F2}") ' Math.Sqrt -- square root Dim area = 144.0 Dim side = Math.Sqrt(area) ' 12.0 lblSide.Text = $"Side length: {side} m" ' Hypotenuse of right triangle: c = sqrt(a^2 + b^2) Dim a = 3.0, b = 4.0 Dim hyp = Math.Sqrt(a * a + b * b) ' 5.0 lblHyp.Text = $"Hypotenuse: {hyp}" ' Guard: Math.Sqrt of negative is Double.NaN Dim x = -4.0 Dim root = Math.Sqrt(x) ' Double.NaN If Double.IsNaN(root) Then lblRoot.Text = "Cannot take sqrt of negative number" End If ' Math.Pow -- x raised to the power y lblPow.Text = Math.Pow(2, 10).ToString() ' 1024 lblPow.Text = Math.Pow(9, 0.5).ToString() ' 3.0 (same as Math.Sqrt(9)) lblPow.Text = Math.Pow(2, -3).ToString() ' 0.125 (1/8) ' VB 2026 operator ^ is equivalent to Math.Pow for most cases Dim result = 2 ^ 10 ' 1024 (same as Math.Pow(2,10)) ' Compound interest: A = P * (1 + r)^n Dim principal = 10000.0 Dim rate = 0.05 Dim years = 10 Dim amount = principal * Math.Pow(1 + rate, years) ' 16288.95 lblAmount.Text = amount.ToString("C2")
18.2 Logarithms
Logarithms are the inverse of exponentiation. VB 2026 provides three logarithm functions. Math.Log(x) computes the natural logarithm (base e), Math.Log10(x) the base-10 log, and Math.Log(x, base) any arbitrary base.
' Math.Log -- natural logarithm (base e) Math.Log(Math.E) ' 1.0 (ln e = 1) Math.Log(1) ' 0.0 (ln 1 = 0) Math.Log(100) ' 4.60517... (ln 100) ' Math.Log10 -- common logarithm (base 10) Math.Log10(1000) ' 3.0 (10^3 = 1000) Math.Log10(0.01) ' -2.0 (10^-2 = 0.01) ' Math.Log(x, base) -- logarithm of any base Math.Log(8, 2) ' 3.0 (2^3 = 8) Math.Log(81, 3) ' 4.0 (3^4 = 81) Math.Log(100, 10) ' 2.0 (same as Log10(100)) ' Practical: how many doublings to reach a target? Private Function DoublingsNeeded(start As Double, target As Double) As Integer If start <= 0 OrElse target <= start Then Return 0 Return CInt(Math.Ceiling(Math.Log(target / start, 2))) End Function ' Population of 1000 doubling to 1 million: lblDoublings.Text = DoublingsNeeded(1000, 1000000).ToString() ' 10 ' Decibel level: dB = 10 * Log10(I / I0) Private Function Decibels(intensity As Double) As Double Dim I0 = 1e-12 ' reference intensity (threshold of hearing) Return Math.Round(10 * Math.Log10(intensity / I0), 1) End Function lbldB.Text = Decibels(0.001).ToString() ' 90.0 dB (busy street)
18.3 Rounding Functions — Floor, Ceiling, Round, Truncate
These four functions all "round" a number, but in very different ways. Confusing them is one of the most common sources of subtle financial calculation bugs in VB programs.
| Function | Rule | 3.7 | 3.2 | -3.7 | -3.2 | 3.5 |
|---|---|---|---|---|---|---|
| Math.Floor(x) | Always toward −∞ | 3 | 3 | -4 | -4 | 3 |
| Math.Ceiling(x) | Always toward +∞ | 4 | 4 | -3 | -3 | 4 |
| Math.Truncate(x) | Always toward zero (chop) | 3 | 3 | -3 | -3 | 3 |
| Math.Round(x) default | Nearest even (banker's) | 4 | 3 | -4 | -3 | 4 |
| Math.Round(x, AwayFromZero) | Round half up (conventional) | 4 | 3 | -4 | -3 | 4 |
' Math.Floor -- always rounds DOWN toward negative infinity Math.Floor(4.9) ' 4 -- chops down Math.Floor(-4.1) ' -5 -- goes MORE negative Math.Floor(4.0) ' 4 -- already integer, unchanged ' Math.Ceiling -- always rounds UP toward positive infinity Math.Ceiling(4.1) ' 5 -- chops up Math.Ceiling(-4.9) ' -4 -- goes LESS negative Math.Ceiling(4.0) ' 4 -- already integer, unchanged ' Math.Truncate -- drops the fractional part (toward zero) Math.Truncate(4.9) ' 4 -- same as Floor for positive Math.Truncate(-4.9) ' -4 -- DIFFERENT from Floor for negative ' Math.Round -- banker's rounding by default (half rounds to even) Math.Round(2.5) ' 2 -- rounds to even (NOT 3!) Math.Round(3.5) ' 4 -- rounds to even Math.Round(4.5) ' 4 -- rounds to even (NOT 5!) ' Use AwayFromZero for conventional "round half up" behaviour Math.Round(2.5, MidpointRounding.AwayFromZero) ' 3 (expected!) Math.Round(3.5, MidpointRounding.AwayFromZero) ' 4 Math.Round(4.5, MidpointRounding.AwayFromZero) ' 5 ' Round to N decimal places Math.Round(3.14159, 2) ' 3.14 Math.Round(3.14159, 4) ' 3.1416 Math.Round(3.145, 2, MidpointRounding.AwayFromZero) ' 3.15 ' Practical: price rounding for retail (always round up) Private Function RoundUpPrice(price As Decimal) As Decimal Return CDec(Math.Ceiling(CDbl(price) * 100) / 100) End Function RoundUpPrice(9.901) ' 9.91 RoundUpPrice(9.900) ' 9.90
Enter any decimal number and see all four rounding methods side by side. The number line shows exactly where each function lands.
18.4 Min, Max, Sign, and Clamp
' Math.Max and Math.Min Dim a = 12, b = 7 lblMax.Text = Math.Max(a, b).ToString() ' 12 lblMin.Text = Math.Min(a, b).ToString() ' 7 ' Clamp: keep value within [lo, hi] using Min and Max Private Function Clamp(value As Double, lo As Double, hi As Double) As Double Return Math.Max(lo, Math.Min(hi, value)) End Function Clamp(-5, 0, 100) ' 0 (below minimum) Clamp(42, 0, 100) ' 42 (within range) Clamp(150, 0, 100) ' 100 (above maximum) ' .NET 6+ also has Math.Clamp directly: Math.Clamp(150, 0, 100) ' 100 ' Math.Sign -- returns -1, 0, or 1 Math.Sign(-42) ' -1 Math.Sign(0) ' 0 Math.Sign(42) ' 1 ' Practical: determine trend direction Dim change = currentPrice - previousPrice Dim trend = Math.Sign(change) Select Case trend Case 1 : lblTrend.Text = "Rising" Case -1 : lblTrend.Text = "Falling" Case Else: lblTrend.Text = "Unchanged" End Select ' Chain Min/Max to find largest of four values Dim biggest = Math.Max(Math.Max(5, 3), Math.Max(8, 1)) ' 8
18.5 Random Numbers
VB 2026 provides two ways to generate random numbers: the classic Rnd() / Randomize() approach (kept for VB6 compatibility) and the modern Random class. For new code, always use Random or Random.Shared (thread-safe singleton in .NET 6+).
' Random.Shared -- thread-safe, no instantiation needed (.NET 6+) Dim rng = Random.Shared ' Integer in [0, max) -- note: max is EXCLUSIVE Dim dice = rng.Next(1, 7) ' 1 to 6 inclusive (max = 7 exclusive) Dim card = rng.Next(1, 14) ' 1 to 13 Dim index = rng.Next(arr.Length) ' random valid array index ' Double in [0.0, 1.0) Dim prob = rng.NextDouble() ' e.g. 0.734... ' Scale to a range: Double in [lo, hi) Private Function RandomDouble(lo As Double, hi As Double) As Double Return lo + Random.Shared.NextDouble() * (hi - lo) End Function Dim temp = RandomDouble(-10, 40) ' random temperature -10 to 40 C ' Shuffle an array (Fisher-Yates) Private Sub Shuffle(ByRef arr() As Integer) For i As Integer = arr.Length - 1 To 1 Step -1 Dim j = Random.Shared.Next(i + 1) Dim tmp = arr(i) : arr(i) = arr(j) : arr(j) = tmp Next End Sub ' Random Boolean (coin flip) Dim heads = Random.Shared.Next(2) = 0 ' True 50% of the time ' Seeded Random for reproducible results (testing) Dim seeded = New Random(42) ' same seed = same sequence every run Dim v1 = seeded.Next(100) ' always produces same values ' Legacy VB6 style (avoid in new code) Randomize() ' seed with clock Dim r = CInt(Int((6 * Rnd()) + 1)) ' 1 to 6
Choose any Math function, enter argument(s), and see the VB call, the computation, and the result. Includes Abs, Sqrt, Pow, Log, Log10, Min, Max, Sign, and Clamp.
18.6 Practical Examples
Example 18.1 — Physics Toolkit
' Distance fallen under gravity: d = 0.5 * g * t^2 Private Function FreeFallDistance(t As Double) As Double Const g = 9.81 Return Math.Round(0.5 * g * Math.Pow(t, 2), 3) End Function ' Speed from kinetic energy: v = sqrt(2E/m) Private Function VelocityFromEnergy(energy As Double, mass As Double) As Double If mass <= 0 Then Return 0 Return Math.Round(Math.Sqrt(2 * energy / mass), 3) End Function ' Richter magnitude from energy ratio: M = (2/3) * Log10(E/E0) Private Function RichterMagnitude(energy As Double) As Double Const E0 = 1e4 Return Math.Round((2.0 / 3) * Math.Log10(energy / E0), 1) End Function ' pH from hydrogen ion concentration: pH = -Log10([H+]) Private Function CalculatePH(hConc As Double) As Double If hConc <= 0 Then Return 0 Return Math.Round(-Math.Log10(hConc), 2) End Function
Example 18.2 — Statistics Helpers
' Standard deviation using Math.Sqrt and Math.Pow Private Function StdDev(values() As Double) As Double If values.Length = 0 Then Return 0 Dim mean = values.Average() Dim sumSqDiff = values.Sum(Function(v) Math.Pow(v - mean, 2)) Return Math.Round(Math.Sqrt(sumSqDiff / values.Length), 4) End Function ' Euclidean distance between two 2D points Private Function Distance(x1 As Double, y1 As Double, x2 As Double, y2 As Double) As Double Return Math.Round(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)), 4) End Function ' Normalise a value to [0,1] range Private Function Normalise(value As Double, minVal As Double, maxVal As Double) As Double If maxVal = minVal Then Return 0 Return Math.Round(Math.Clamp((value - minVal) / (maxVal - minVal), 0, 1), 4) End Function
Three random number applications: dice roller, number generator with custom range, and coin-flip probability experiment.
Six science formulas each powered by Math functions. See the VB code and result for free fall, kinetic energy, compound interest, decibels, Richter scale, and pH.
Enter a dataset and compute statistics using Math functions: mean, variance, standard deviation (Math.Sqrt + Math.Pow), range (Math.Max - Math.Min), and normalised values.
18.7 GitHub Copilot — Math Patterns
' Generate a monthly loan amortisation table: principal, rate %, years. For each month show balance, payment, interest portion, and principal portion. Use Math.Pow and Math.Round.'' Loan amortisation table using Math.Pow and Math.Round. Private Sub GenerateAmortTable() Dim P As Decimal : If Not Decimal.TryParse(txtPrincipal.Text, P) Then Return Dim rPct As Double : If Not Double.TryParse(txtRate.Text, rPct) Then Return Dim yrs As Integer : If Not Integer.TryParse(txtYears.Text, yrs) Then Return Dim r = rPct / 100 / 12 ' monthly rate Dim n = yrs * 12 ' total payments Dim pmt = CDec(CDbl(P) * r * Math.Pow(1 + r, n) / (Math.Pow(1 + r, n) - 1)) Dim balance = P Dim totalInterest = 0D dgvAmort.Rows.Clear() For month As Integer = 1 To n Dim interest = Math.Round(balance * CDec(r), 2) Dim principal = Math.Round(pmt - interest, 2) balance = Math.Round(balance - principal, 2) If month = n Then balance = 0 ' eliminate rounding residual totalInterest += interest dgvAmort.Rows.Add(month, pmt.ToString("C2"), interest.ToString("C2"), principal.ToString("C2"), balance.ToString("C2")) Next lblTotal.Text = $"Total interest: {totalInterest:C2}" End Sub
' Use Random.Shared and Math.Pow to estimate Pi with Monte Carlo simulation. Throw N random points in a unit square and check if they fall inside the unit circle.'' Monte Carlo Pi estimation: count random points inside unit circle. Private Function EstimatePi(iterations As Integer) As Double Dim inside = 0 For i As Integer = 1 To iterations Dim x = Random.Shared.NextDouble() ' in [0, 1) Dim y = Random.Shared.NextDouble() ' Point is inside unit circle if distance from origin <= 1 If Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)) <= 1.0 Then inside += 1 End If Next ' Pi/4 = circle area / square area = inside / total Return 4.0 * inside / iterations End Function Private Sub btnEstimate_Click(sender As Object, e As EventArgs) Handles btnEstimate.Click Dim n = CInt(nudIterations.Value) Dim estimate = EstimatePi(n) lblPi.Text = $"Estimate: {estimate:F6}" lblError.Text = $"Error vs Math.PI: {Math.Abs(estimate - Math.PI):F6}" End Sub
Try these in the Copilot Chat panel while working with Math functions:
- "Write a Function BodyMassIndex(weight As Double, heightM As Double) that returns BMI and a String category using Math.Round and If..ElseIf"
- "Generate 1000 normally-distributed random numbers using Box-Muller transform with Math.Sqrt, Math.Log, and Math.Cos"
- "Calculate the standard deviation, variance, and z-scores for a Double array using Math.Pow, Math.Sqrt, and LINQ"
- "Build a mortgage amortisation schedule into a DataGridView using Math.Pow for the monthly payment formula"
Lesson Summary
- All math functions are in
System.Math(justMathin VB). ConstantsMath.PIandMath.Eprovide the full double-precision values of π and Euler's number. Math.Absremoves the sign;Math.Sqrt(x)returns the square root (returnsDouble.NaNfor negative x, not an exception);Math.Pow(x, y)raises x to y, equivalent to the^operator.Math.Log(x)is the natural log (base e).Math.Log10(x)is base-10.Math.Log(x, base)computes any base. All returnDouble.NegativeInfinityfor x=0 andDouble.NaNfor negative x.- Rounding:
Math.Flooralways goes down;Math.Ceilingalways goes up;Math.Truncatealways goes toward zero;Math.Rounddefaults to banker's rounding. UseMidpointRounding.AwayFromZerofor conventional half-up behaviour. Math.MaxandMath.Minwork on any numeric type. Use them in combination to clamp a value:Math.Max(lo, Math.Min(hi, value))orMath.Clamp(value, lo, hi)(.NET 6+).- Use
Random.Sharedfor random numbers in .NET 6+..Next(min, max)generates integers where max is exclusive..NextDouble()returns [0.0, 1.0). Use a seededNew Random(seed)for reproducible tests.
Exercises
Exercise 18.1 — Geometry Calculator
- Write a form with radio buttons for shape: Circle, Rectangle, Triangle, Sphere
- For each shape compute area and perimeter/volume using
Math.PI,Math.Sqrt,Math.Pow - Circle: Area = πr², Circumference = 2πr
- Triangle (Heron's): Area =
Math.Sqrt(s*(s-a)*(s-b)*(s-c))where s = semi-perimeter - Sphere: Volume = (4/3)πr³, Surface = 4πr²
- Copilot challenge: Ask Copilot to "add an Ellipse option with area = Math.PI * a * b"
Exercise 18.2 — Financial Rounding Suite
- Create a price calculator that applies a 6% SST to a subtotal using
Math.Round(x, 2, AwayFromZero) - Show the difference between Floor, Ceiling, Round (default), and Round (AwayFromZero) for the same price
- Add a currency converter that uses
Math.Roundto display values to 4 decimal places - Demonstrate why banker's rounding reduces systematic bias by summing 10 x.5 values with both rounding modes
- Copilot challenge: Ask Copilot to "add a loan payment calculator showing total interest using Math.Pow"
Exercise 18.3 — Random Number Games
- Build a lottery number picker: choose 6 unique numbers from 1-49 using
Random.Shared - Add a Monte Carlo Pi estimator: throw N random points, count those inside unit circle, estimate π
- Simulate rolling two d6 1000 times, tally each sum (2-12), and display a text histogram showing the normal distribution shape
- Copilot challenge: Ask Copilot to "use Random.Shared.GetItems to pick lottery numbers without repeats (.NET 8+)"
Related Resources
← Lesson 17
Functions — user-defined, overloading, recursion.
Lesson 19 →
Trigonometric Functions — Sin, Cos, Tan and more.
MS Docs — System.Math
Complete reference for all Math class members in .NET 10.
MS Docs — System.Random
Random class documentation including Random.Shared.
Featured Books
Visual Basic 2022 Made Easy
Practical Math function exercises including geometry tools, financial calculators, and physics simulations.
View on Amazon →
VB Programming With Code Examples
48 programs making extensive use of Math functions for scientific and business calculations.
View on Amazon →