## 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.