Numbers and Math
Prerequisites: Data types
Arithmetic operators
Module Program
Sub Main()
Console.WriteLine(7 + 3)
Console.WriteLine(7 - 3)
Console.WriteLine(7 * 3)
Console.WriteLine(7 / 2) ' always floating-point division
Console.WriteLine(7 \ 2) ' integer division
Console.WriteLine(7 Mod 2) ' remainder
Console.WriteLine(2 ^ 10) ' power (a Double)
Console.WriteLine(-7 \ 2)
End Sub
End Module
10
4
21
3.5
3
1
1024
-3
Unlike C-style languages, / in VB always produces a floating-point
result, even for two integers. Use \ for integer division; it
truncates toward zero.
The Math class
Module Program
Sub Main()
Console.WriteLine(Math.Sqrt(16))
Console.WriteLine(Math.Abs(-5))
Console.WriteLine(Math.Max(3, 9))
Console.WriteLine(Math.Round(2.5))
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero))
Console.WriteLine(Math.Round(3.14159, 2))
Console.WriteLine(Math.Floor(2.7))
Console.WriteLine(Math.Ceiling(2.1))
Console.WriteLine(Math.PI)
End Sub
End Module
4
5
9
2
3
3.14
2
3
3.141592653589793
Math.Round uses banker's rounding by default (2.5 becomes 2); pass
MidpointRounding.AwayFromZero for the school rule.
Overflow is checked
Module Program
Sub Main()
Dim big As Integer = Integer.MaxValue
Console.WriteLine(big)
Dim asLong As Long = CLng(big) + 1
Console.WriteLine(asLong)
big += 1
Console.WriteLine("never printed")
End Sub
End Module
2147483647
2147483648
Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow.
at Demo.Program.Main()
VB checks integer overflow by default and throws an
OverflowException instead of silently wrapping around. Use Long (or
System.Numerics.BigInteger) for bigger values.
Decimal for money
Module Program
Sub Main()
Console.WriteLine(0.1 + 0.2 = 0.3)
Console.WriteLine(0.1D + 0.2D = 0.3D)
Dim price = 19.99D
Console.WriteLine(price * 3)
End Sub
End Module
False
True
59.97
Random numbers
Module Program
Sub Main()
Dim rng As New Random(42) ' fixed seed: same numbers every run
Dim a = rng.Next(1, 7)
Dim b = rng.Next(1, 7)
Console.WriteLine(a >= 1 AndAlso a <= 6)
Console.WriteLine(b >= 1 AndAlso b <= 6)
End Sub
End Module
True
True
Next(1, 7) returns 1 to 6 — the upper bound is exclusive. Use
Random.Shared.Next(1, 7) for everyday randomness without creating an
object; a seed is useful for repeatable tests. (Older code uses VB6's
Randomize and Rnd.)
Practice
Convert 100 minutes into hours and minutes using \ and Mod, and
compute the area of a circle with radius 3 rounded to two decimals.
Show solution
Module Program
Sub Main()
Dim minutes = 100
Console.WriteLine($"{minutes \ 60} h {minutes Mod 60} min")
Console.WriteLine(Math.Round(Math.PI * 3 ^ 2, 2))
End Sub
End Module
1 h 40 min
28.27