## C# || How To Round A Number To The Nearest X Using C# The following is a module with functions which demonstrates how to round a number to the nearest X using C#.

This function has the ability to either round a number to the nearest amount, always round up, or always round down. For example, when dealing with money, this is good for rounding a dollar amount to the nearest 5 cents.

1. Round – Nearest

The example below demonstrates the use of ‘Utils.Round.Amount‘ to round a number to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.

``` 1. Round - Nearest C# // Round - Nearest // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round to nearest amount foreach (var value in values) { Console.WriteLine(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount)}"); } // expected output: /* Value: 19.28, Rounded: 19.3 Value: 31.22, Rounded: 31.2 Value: 19.91, Rounded: 19.9 Value: 19.87, Rounded: 19.85 Value: 0.05, Rounded: 0.05 */ 123456789101112131415161718192021 // Round - Nearest // Declare values to roundvar values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amountvar stepAmount = 0.05M; // Round to nearest amountforeach (var value in values) {    Console.WriteLine(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount)}");} // expected output:/*    Value: 19.28, Rounded: 19.3    Value: 31.22, Rounded: 31.2    Value: 19.91, Rounded: 19.9    Value: 19.87, Rounded: 19.85    Value: 0.05, Rounded: 0.05*/ ```

2. Round – Up

The example below demonstrates the use of ‘Utils.Round.Amount‘ to always round a number up to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.

``` 2. Round - Up C# // Round - Up // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round up to nearest amount foreach (var value in values) { Console.WriteLine(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Up)}"); } // expected output: /* Value: 19.28, Rounded: 19.3 Value: 31.22, Rounded: 31.25 Value: 19.91, Rounded: 19.95 Value: 19.87, Rounded: 19.9 Value: 0.05, Rounded: 0.05 */ 123456789101112131415161718192021 // Round - Up // Declare values to roundvar values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amountvar stepAmount = 0.05M; // Round up to nearest amountforeach (var value in values) {    Console.WriteLine(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Up)}");} // expected output:/*    Value: 19.28, Rounded: 19.3    Value: 31.22, Rounded: 31.25    Value: 19.91, Rounded: 19.95    Value: 19.87, Rounded: 19.9    Value: 0.05, Rounded: 0.05*/ ```

3. Round – Down

The example below demonstrates the use of ‘Utils.Round.Amount‘ to always round a number down to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.

``` 3. Round - Down C# // Round - Down // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round down to nearest amount foreach (var value in values) { Console.WriteLine(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Down)}"); } // expected output: /* Value: 19.28, Rounded: 19.25 Value: 31.22, Rounded: 31.2 Value: 19.91, Rounded: 19.9 Value: 19.87, Rounded: 19.85 Value: 0.05, Rounded: 0.05 */ 123456789101112131415161718192021 // Round - Down  // Declare values to roundvar values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amountvar stepAmount = 0.05M; // Round down to nearest amountforeach (var value in values) {    Console.WriteLine(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Down)}");} // expected output:/*    Value: 19.28, Rounded: 19.25    Value: 31.22, Rounded: 31.2    Value: 19.91, Rounded: 19.9    Value: 19.87, Rounded: 19.85    Value: 0.05, Rounded: 0.05*/ ```

4. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!

``` Utils Namespace C# // ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Round { public enum Type { Nearest, Up, Down } /// <summary> /// Rounds a number to the nearest X /// </summary> /// <param name="value">The value to round</param> /// <param name="stepAmount">The amount to round the value by</param> /// <param name="type">The type of rounding to perform</param> /// <returns>The value rounded by the step amount and type</returns> public static decimal Amount(decimal value, decimal stepAmount , Round.Type type = Round.Type.Nearest) { var inverse = 1 / stepAmount; var dividend = value * inverse; switch (type) { case Round.Type.Nearest: dividend = Math.Round(dividend); break; case Round.Type.Up: dividend = Math.Ceiling(dividend); break; case Round.Type.Down: dividend = Math.Floor(dividend); break; default: throw new ArgumentException(\$"Unknown type: {type}", nameof(type)); } var result = dividend / inverse; return result; } } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 14, 2021//    Taken From: http://programmingnotes.org///    File:  Utils.cs//    Description: Handles general utility functions// ============================================================================using System; namespace Utils {    public static class Round {        public enum Type {            Nearest,            Up,            Down        }         /// <summary>        /// Rounds a number to the nearest X        /// </summary>        /// <param name="value">The value to round</param>         /// <param name="stepAmount">The amount to round the value by</param>        /// <param name="type">The type of rounding to perform</param>        /// <returns>The value rounded by the step amount and type</returns>        public static decimal Amount(decimal value, decimal stepAmount                    , Round.Type type = Round.Type.Nearest) {            var inverse = 1 / stepAmount;            var dividend = value * inverse;            switch (type) {                case Round.Type.Nearest:                    dividend = Math.Round(dividend);                    break;                case Round.Type.Up:                    dividend = Math.Ceiling(dividend);                    break;                case Round.Type.Down:                    dividend = Math.Floor(dividend);                    break;                default:                    throw new ArgumentException(\$"Unknown type: {type}", nameof(type));            }            var result = dividend / inverse;            return result;        }    }}// http://programmingnotes.org/ ```

5. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

``` More Examples C# // ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round to nearest amount foreach (var value in values) { Display(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount)}"); } Display(""); // Round up to nearest amount foreach (var value in values) { Display(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Up)}"); } Display(""); // Round down to nearest amount foreach (var value in values) { Display(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Down)}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 14, 2021//    Taken From: http://programmingnotes.org///    File:  Program.cs//    Description: The following demonstrates the use of the Utils Namespace// ============================================================================using System;using System.Diagnostics; public class Program {    static void Main(string[] args) {        try {            // Declare values to round            var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M };             // Declare step amount            var stepAmount = 0.05M;             // Round to nearest amount            foreach (var value in values) {                Display(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount)}");            }             Display("");             // Round up to nearest amount            foreach (var value in values) {                Display(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Up)}");            }             Display("");             // Round down to nearest amount            foreach (var value in values) {                Display(\$"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Down)}");            }        } catch (Exception ex) {            Display(ex.ToString());        } finally {            Console.ReadLine();        }    }     static void Display(string message) {        Console.WriteLine(message);        Debug.Print(message);    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

## VB.NET || How To Round A Number To The Nearest X Using VB.NET The following is a module with functions which demonstrates how to round a number to the nearest X using VB.NET.

This function has the ability to either round a number to the nearest amount, always round up, or always round down. For example, when dealing with money, this is good for rounding a dollar amount to the nearest 5 cents.

1. Round – Nearest

The example below demonstrates the use of ‘Utils.RoundAmount‘ to round a number to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.

``` 1. Round - Nearest Visual Basic .NET ' Round - Nearest ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round to nearest amount For Each value In values Debug.Print(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount)}") Next ' expected output: ' Value: 19.28, Rounded: 19.3 ' Value: 31.22, Rounded: 31.2 ' Value: 19.91, Rounded: 19.9 ' Value: 19.87, Rounded: 19.85 ' Value: 0.05, Rounded: 0.05 12345678910111213141516171819 ' Round - Nearest ' Declare values to roundDim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amountDim stepAmount = 0.05D ' Round to nearest amountFor Each value In values    Debug.Print(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount)}")Next ' expected output:'    Value: 19.28, Rounded: 19.3'    Value: 31.22, Rounded: 31.2'    Value: 19.91, Rounded: 19.9'    Value: 19.87, Rounded: 19.85'    Value: 0.05, Rounded: 0.05 ```

2. Round – Up

The example below demonstrates the use of ‘Utils.RoundAmount‘ to always round a number up to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.

``` 2. Round - Up Visual Basic .NET ' Round - Up ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round up to nearest amount For Each value In values Debug.Print(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Up)}") Next ' expected output: ' Value: 19.28, Rounded: 19.3 ' Value: 31.22, Rounded: 31.25 ' Value: 19.91, Rounded: 19.95 ' Value: 19.87, Rounded: 19.9 ' Value: 0.05, Rounded: 0.05 12345678910111213141516171819 ' Round - Up ' Declare values to roundDim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amountDim stepAmount = 0.05D ' Round up to nearest amountFor Each value In values    Debug.Print(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Up)}")Next ' expected output:'    Value: 19.28, Rounded: 19.3'    Value: 31.22, Rounded: 31.25'    Value: 19.91, Rounded: 19.95'    Value: 19.87, Rounded: 19.9'    Value: 0.05, Rounded: 0.05 ```

3. Round – Down

The example below demonstrates the use of ‘Utils.RoundAmount‘ to always round a number down to the nearest 5 cents.

The optional function parameter determines they type of rounding to perform.

``` 3. Round - Down Visual Basic .NET ' Round - Down ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round down to nearest amount For Each value In values Debug.Print(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Down)}") Next ' expected output: ' Value: 19.28, Rounded: 19.25 ' Value: 31.22, Rounded: 31.2 ' Value: 19.91, Rounded: 19.9 ' Value: 19.87, Rounded: 19.85 ' Value: 0.05, Rounded: 0.05 12345678910111213141516171819 ' Round - Down  ' Declare values to roundDim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amountDim stepAmount = 0.05D ' Round down to nearest amountFor Each value In values    Debug.Print(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Down)}")Next ' expected output:'    Value: 19.28, Rounded: 19.25'    Value: 31.22, Rounded: 31.2'    Value: 19.91, Rounded: 19.9'    Value: 19.87, Rounded: 19.85'    Value: 0.05, Rounded: 0.05 ```

4. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!

``` Utils Namespace Visual Basic .NET ' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 1, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Enum RoundType Nearest Up Down End Enum ''' <summary> ''' Rounds a number to the nearest X ''' </summary> ''' <param name="value">The value to round</param> ''' <param name="stepAmount">The amount to round the value by</param> ''' <param name="type">The type of rounding to perform</param> ''' <returns>The value rounded by the step amount and type</returns> Public Function RoundAmount(value As Decimal, stepAmount As Decimal _ , Optional type As RoundType = RoundType.Nearest) As Decimal Dim inverse = 1 / stepAmount Dim dividend = value * inverse Select Case type Case RoundType.Nearest dividend = Math.Round(dividend) Case RoundType.Up dividend = Math.Ceiling(dividend) Case RoundType.Down dividend = Math.Floor(dividend) Case Else Throw New ArgumentException(\$"Unknown type: {type}", NameOf(type)) End Select Dim result = dividend / inverse Return result End Function End Module End Namespace ' http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 ' ============================================================================'    Author: Kenneth Perkins'    Date:   Dec 1, 2020'    Taken From: http://programmingnotes.org/'    File: Utils.vb'    Description: Handles general utility functions' ============================================================================Option Strict OnOption Explicit On Namespace Global.Utils    Public Module modUtils        Public Enum RoundType            Nearest            Up            Down        End Enum         ''' <summary>        ''' Rounds a number to the nearest X        ''' </summary>        ''' <param name="value">The value to round</param>         ''' <param name="stepAmount">The amount to round the value by</param>        ''' <param name="type">The type of rounding to perform</param>        ''' <returns>The value rounded by the step amount and type</returns>        Public Function RoundAmount(value As Decimal, stepAmount As Decimal _                    , Optional type As RoundType = RoundType.Nearest) As Decimal            Dim inverse = 1 / stepAmount            Dim dividend = value * inverse            Select Case type                Case RoundType.Nearest                    dividend = Math.Round(dividend)                Case RoundType.Up                    dividend = Math.Ceiling(dividend)                Case RoundType.Down                    dividend = Math.Floor(dividend)                Case Else                    Throw New ArgumentException(\$"Unknown type: {type}", NameOf(type))            End Select            Dim result = dividend / inverse            Return result        End Function    End ModuleEnd Namespace ' http://programmingnotes.org/ ```

5. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

``` More Examples Visual Basic .NET ' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 1, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round to nearest amount For Each value In values Display(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount)}") Next Display("") ' Round up to nearest amount For Each value In values Display(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Up)}") Next Display("") ' Round down to nearest amount For Each value In values Display(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Down)}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 ' ============================================================================'    Author: Kenneth Perkins'    Date:   Dec 1, 2020'    Taken From: http://programmingnotes.org/'    File: Program.vb'    Description: The following demonstrates the use of the Utils Namespace' ============================================================================Option Strict OnOption Explicit OnImports System Public Module Program    Sub Main(args As String())        Try            ' Declare values to round            Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D}             ' Declare step amount            Dim stepAmount = 0.05D             ' Round to nearest amount            For Each value In values                Display(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount)}")            Next             Display("")             ' Round up to nearest amount            For Each value In values                Display(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Up)}")            Next             Display("")             ' Round down to nearest amount            For Each value In values                Display(\$"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Down)}")            Next        Catch ex As Exception            Display(ex.ToString)        Finally            Console.ReadLine()        End Try    End Sub     Public Sub Display(message As String)        Console.WriteLine(message)        Debug.Print(message)    End SubEnd Module ' http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.