C# Math Round(Double, MidpointRounding)

Description

Math Round(Double, MidpointRounding) 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

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


public static double Round(
  double value,
  MidpointRounding mode
)

Parameters

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

  • value - A double-precision floating-point number to be rounded.
  • mode - Specification for how to round value if it is midway between two other numbers.

Returns

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

Example

In the following example, because the floating-point value .1 has no finite binary representation, the first call to the Round(Double) method with a value of 11.5 returns 11 instead of 12.


using System;/*  ww w  .ja v a  2 s  .com*/

public class Example
{
   public static void Main()
   {
      double value = 11.1;
      for (int ctr = 0; ctr <= 5; ctr++){
         value = RoundValueAndAdd(value);
      }
      value = 11.5;
      RoundValueAndAdd(value);
   }

   private static double RoundValueAndAdd(double value)
   {
      Console.WriteLine("{0} --> {1}", value, Math.Round(value, 
                        MidpointRounding.AwayFromZero));
      return value + .1;
   }
}

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