Open In App

C# | Math.Round() Method | Set – 2

Improve
Improve
Like Article
Like
Save
Share
Report

In C#, Math.Round() is a Math class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method has another overload with which, you can specify the number of digits beyond the decimal point in the returned value. It returns the nearest value of the number with the precision equal to the second parameter passed. If the value to round is exactly halfway between an even and an odd number, then the even number is returned. Math.Round applies IEEE Standard 754, section 4.

This method can be overloaded by changing the number and type of the arguments passed. There are total 8 methods in the overload list of the Math.Round() method in which 4 has already been discussed in C# | Math.Round() Method | Set – 1.

  1. Math.Round(Double)
  2. Math.Round(Double, Int32)
  3. Math.Round(Decimal)
  4. Math.Round(Decimal, Int32)
  5. Math.Round(Double, Int32, MidpointRounding)
  6. Math.Round(Double, MidpointRounding)
  7. Math.Round(Decimal, Int32, MidpointRounding)
  8. Math.Round(Decimal, MidpointRounding)

Math.Round(Double, Int32, MidpointRounding)

This method is used to rounds a double precision floating-point value to a specified number of fractional digits. A parameter specifies how to round the value if it is midway between two numbers.

Syntax:

public static double Round (double val, int digits, MidpointRounding mode);

Parameters:

val: It is the required double-precision floating-point number which is to be rounded and type of this parameter is System.Double.

digits: It is the number of fractional digits in the return value and type of this parameter is System.Int32.

mode: Specification for how to round val if it is midway between two other numbers and works as MidpointRounding.

Return Type: This method returns the number nearest to val that has a number of fractional digits equal to digits. If the val has fewer fractional digits than digits, val is returned unchanged. Return type of this method is System.Double.

Exceptions:

  • ArgumentOutOfRangeException: If the digit is less than 0 or greater than 15.
  • ArgumentException: If the mode is not a valid value of MidpointRounding.

Example:




// C# program to demonstrate the 
// Math.Round(Double, Int32, 
// MidpointRounding) method
using System;
   
class Geeks 
{
      
    // Main Method
    public static void Main() 
    {
        // The 4 values are store in an double
        // type array name 'val'
        double[] val = {4.125, 4.135, 4.165, 4.175};
          
   
        Console.WriteLine("Rounded values are:"); 
          
        // 'foreach' loop iterates through
        // each item from the array 'values' 
        // and storing the items in a new 
        // variable 'val' 
        foreach(double value in val) 
          
            // '{0}' specify the variable 'val' which is
            // in 'foreach' loop and '{1}' specify the 
            // rounded value, here '2' defines the number
            // of digit after point, e.g. 4.135 == 4.14,
            // after '4.' there is 2 digits'.14' 
            // and here '.ToEven' select the nearest even
            // number e.g 4.125 == 4.12, here nearest even
            // number is '12',
            Console.WriteLine("{0} == {1}", value, Math.Round(value, 2, 
                                             MidpointRounding.ToEven));
              
    }
}


Output:

Rounded values are:
4.125 == 4.12
4.135 == 4.14
4.165 == 4.16
4.175 == 4.18

Note: In some cases this method may not appear to round midpoint values as specified by the mode parameter due to the loss of precision which can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values. This is illustrated in the above example, where 4.135 is rounded to 4.13 instead of 4.14. This occurs because internally the method multiplies val by 10digits, and the multiplication operation, in this case, suffers from a loss of precision.

Math.Round(Double, MidpointRounding)

This method is used to rounds a double precision floating-point value to the nearest integer. A parameter specifies how to round the value if it is midway between two numbers.

Syntax:

public static double Round (double val, MidpointRounding mode);

Parameters:

val: It is the required double-precision floating-point number which is to be rounded and type of this parameter is System.Double.

mode: Specification for how to round val if it is midway between two other numbers and works as MidpointRounding.

Return Type: This method returns the integer nearest value. If the val is halfway between two integers, one of which is even and the other odd, then mode determines which of the two is returned. The return type of this method is System.Double.

Exception: This method gives ArgumentException if the mode is not a valid value of MidpointRounding.

Example:




// C# program to demonstrate the 
// Math.Round(Double, MidpointRounding) method
using System;
   
class Geeks 
{
      
    // Main Method
    public static void Main() 
    {
          
        //'val' is double type variable 
        // which holds the value 4.1
        double val = 4.1;
          
        Console.WriteLine("Inside Loop:\n");
          
        //'for loop', it execute the next
        // output for 8 times
        for (int i = 0; i <= 8; i++) 
        {
              
            // '{0}' specify the variable 'val' and 
            // '{1}' specify the rounded value
            Console.WriteLine("{0} = {1}", val, Math.Round(val, 
                               MidpointRounding.AwayFromZero));
              
            // increment 'val' by '0.1'                
            val += 0.1; 
        }
          
        // a new value is assigned
        // to variable 'val'
        val = 4.5; 
          
        // prints a new line
        Console.WriteLine(); 
          
        //'{0}'specify the variable 'val' in which a new
        // value 4.5 is assigned and '{1}' specify the 
        // new rounded value
        Console.WriteLine("Outside Loop : {0} = {1}", val, 
          Math.Round(val, MidpointRounding.AwayFromZero));
            
    }
}


Output:

Inside Loop:

4.1 = 4
4.2 = 4
4.3 = 4
4.4 = 4
4.5 = 4
4.6 = 5
4.7 = 5
4.8 = 5
4.9 = 5

Outside Loop : 4.5 = 5

Note: In some cases this method may not appear to round midpoint values to the nearest even integer due to the loss of precision which can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values. In the above example, because the floating-point value 0.1 has no finite binary representation, the first call to the method with a value of 4.5 returns 4 instead of 5.

Math.Round(Decimal, Int32, MidpointRounding)

This method is used to round a decimal value to a specified number of fractional digits. A parameter specifies how to round the value if it is midway between two numbers.

Syntax:

public static decimal Round (decimal val, int num, MidpointRounding mode);

Parameters:

val: It is the required decimal number of type System.Decimal which is to be rounded.
num: It specifies the number of decimal places in the return value and type of this parameter is System.Int32.
mode: It provides specification for how to round val if it is midway between two other numbers.

Return Type: The number nearest to val that contains a number of fractional digits equal to num. If val has fewer fractional digits than decimals, val is returned unchanged.

Exceptions:

  • ArgumentOutOfRangeException: If the num is less than 0 or greater than 28.
  • ArgumentException: If the mode is not a valid value of MidpointRounding.
  • OverflowException: If the result is outside the range of a Decimal.

Example:




// C# program to demonstrate the 
// Math.Round(Decimal, Int32, 
// MidpointRounding) method
using System;
  
class Geeks 
{
      
    // Main Method
    public static void Main() 
    {
  
        // The 6 values are store in an 
        // double type array name val,
        double[] val = {2.275, 2.375, 2.455, 
                        3.525, 3.635, 3.465 };
                          
        // prints 'Rounded values :'
        Console.WriteLine("Rounded Values: "); 
  
        //'foreach' loop iterates through each item
        // from the array 'val' and storing the items
        // in a new variable 'value'
        foreach(double value in val) 
  
            // '{0}' specify the variable 'value'and 
            // '{1}' specify the rounded value,
            Console.WriteLine("{0} == {1}", value, Math.Round(value, 
                                        2, MidpointRounding.ToEven));
          
    }
}


Output:

Rounded Values: 
2.275 == 2.28
2.375 == 2.38
2.455 == 2.46
3.525 == 3.52
3.635 == 3.64
3.465 == 3.46

Math.Round(Decimal, MidpointRounding)

This method is used to round a decimal value to the nearest integer. A parameter specifies how to round the value if it is midway between two numbers.

Syntax:

public static decimal Round (decimal val, MidpointRounding mode);

Parameters:

val: It is the required decimal number of type System.Decimal which is to be rounded.
mode: It provides specification for how to round val if it is midway between two other numbers.

Return Type: It returns the integer nearest val. If val is halfway between two numbers, one of which is even and the other odd, then mode determines which of the two is returned.

Exceptions:

  • ArgumentException: If the mode is not a valid value of MidpointRounding.
  • OverflowException: If the result is outside the range of a Decimal.

Example:




// C# program to demonstrate the 
// Math.Round(Decimal, MidpointRounding) method
using System;
  
class Geeks 
{
      
    // Main Method
    public static void Main() 
    {
          
        // The 6 values are store in a 
        // double type array name val
        double[] val = {2.275, 2.375, 2.455, 
                       3.525, 3.635, 3.465 };
          
        // prints 'Rounded values :'
        Console.WriteLine("Rounded values :"); 
  
        //'foreach' loop iterates through each item 
        // from the array 'val' and storing the items 
        // in a new variable 'value' 
        foreach(double value in val) 
  
            // '{0}' specify the variable 'value' and
            // '{1}' specify the rounded value
            Console.WriteLine("{0} == {1}", value, Math.Round(value, 
                                           MidpointRounding.ToEven));
    }
}


Output:

Rounded values :
2.275 == 2
2.375 == 2
2.455 == 2
3.525 == 4
3.635 == 4
3.465 == 3

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.7.2



Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads