C# Math Round(Decimal, MidpointRounding)

Description

Math Round(Decimal, MidpointRounding) rounds a decimal value to the nearest integer. A parameter specifies how to round the value if it is midway between two numbers.

Syntax

Math.Round(Decimal, MidpointRounding) has the following syntax.


public static decimal Round(
  decimal d,
  MidpointRounding mode
)

Parameters

Math.Round(Decimal, MidpointRounding) has the following parameters.

  • d - A decimal number to be rounded.
  • mode - Specification for how to round d if it is midway between two other numbers.

Returns

Math.Round(Decimal, MidpointRounding) method returns The integer nearest d. If d is halfway between two numbers, one of which is even and the other odd, then mode determines which of the two is returned.

Example

The following code shows how to use Math.Round(Decimal, MidpointRounding) method.


using System;//from  www .  ja  v a 2 s .c  o m

public class Example
{
   public static void Main()
   {
      decimal[] values = { 2.125M, 2.135M, 2.145M, 3.125M, 3.135M, 3.145M };
      foreach (double value in values)
         Console.WriteLine("{0} --> {1}", value, Math.Round(value, MidpointRounding.AwayFromZero));

   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version