Home
VB.NET
Math.Round Example
Updated Nov 23, 2021
Dot Net Perls
Math.Round. In .NET, the Math.Round function provides built-in logic. With the MidpointRounding enum we round with special options—away from zero, or to even.
Enum
Function notes. Numbers can be rounded in many ways. The Math.Round function has forms that act on many numeric types, including Double and Decimal.
Double
Rounding output. Consider the Double 1.234. When we call the Math.Round function on it, we receive the number 1—the fractional part was rounded down.
1.234 -> 1
Example. This program calls Math.Round on the Double 123.45. To call Math.Round With no options, we use just one argument. This rounds the number to 123.
And With a second argument of 1, we round to one decimal place. This yields the values 123.5 (for AwayFromZero) and 123.4 (for ToEven).
Detail With a positive number, this option will round up—so 123.45 becomes 123.5.
Detail This will round to an even number—so 123.45 becomes 123.4 because 4 is an even number and 5 is not.
Module Module1 Sub Main() ' Call Math.Round on this Double. Dim before As Double = 123.45 Dim after1 As Double = Math.Round(before, 1, MidpointRounding.AwayFromZero) Dim after2 As Double = Math.Round(before, 1, MidpointRounding.ToEven) Dim after3 As Double = Math.Round(before) Console.WriteLine(before) Console.WriteLine(after1) Console.WriteLine(after2) Console.WriteLine(after3) Console.WriteLine() ' Use on this Decimal. Dim before2 As Decimal = 125.101 Dim after4 As Decimal = Math.Round(before2) Dim after5 As Decimal = Math.Round(before2, 1) Console.WriteLine(before2) Console.WriteLine(after4) Console.WriteLine(after5) End Sub End Module
123.45 123.5 123.4 123 125.101 125 125.1
Notes, program. We also use Math.Round on the Decimal type. These have the same results as the Double type. The Math Class supports many numeric types, including Double and Decimal and others.
Decimal
Also It is possible to provide 2 arguments to Math.Round. The second Integer specifies the number of decimal places to round to.
Integer
Summary. Rounding functionality is available in .NET. It is not needed to develop custom Functions in most programs. We instead invoke the Math.Round Shared Function, with 1 to 3 arguments.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 23, 2021 (image).
Home
Changes
© 2007-2025 Sam Allen