Math.Round Math.Round Math.Round Math.Round Method

定义

将值舍入到最接近的整数或指定的小数位数。Rounds a value to the nearest integer or to the specified number of fractional digits.

重载

Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding)

将小数值舍入到指定数量的小数位,并为中点值使用指定的舍入规则。Rounds a decimal value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding)

将双精度浮点值舍入到指定数量的小数位,并为中点值使用指定的舍入规则。Rounds a double-precision floating-point value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding)

将双精度浮点值舍入到最接近的整数,并为中点值使用指定的舍入约定。Rounds a double-precision floating-point value to the nearest integer, and uses the specified rounding convention for midpoint values.

Round(Double, Int32) Round(Double, Int32) Round(Double, Int32) Round(Double, Int32)

将双精度浮点值舍入到指定数量的小数位,并将中点值舍入到最接近的偶数。Rounds a double-precision floating-point value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

Round(Double) Round(Double) Round(Double) Round(Double)

将双精度浮点值舍入到最接近的整数值,并将中点值舍入到最接近的偶数。Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.

Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32)

将小数值舍入到指定数量的小数位,并将中点值舍入到最接近的偶数。Rounds a decimal value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

Round(Decimal) Round(Decimal) Round(Decimal) Round(Decimal)

将小数值舍入到最接近的整数值,并将中点值舍入到最接近的偶数。Rounds a decimal value to the nearest integral value, and rounds midpoint values to the nearest even number.

Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding)

将小数值舍入到最接近的整数,并为中点值使用指定的舍入规则。Rounds a decimal value to the nearest integer, and uses the specified rounding convention for midpoint values.

示例

除了中的示例之外备注部分中,这篇文章包括示例,介绍的以下重载Math.Round方法:In addition to the examples in the Remarks section, this article includes examples that illustrate the following overloads of the Math.Round method:

Math.Round(Decimal)Math.Round(Decimal)
Math.Round(Double)Math.Round(Double)
Math.Round(Decimal, Int32)Math.Round(Decimal, Int32)
Math.Round(Decimal, MidpointRounding)Math.Round(Decimal, MidpointRounding)
Math.Round(Double, Int32)Math.Round(Double, Int32)
Math.Round(Double, MidpointRounding)Math.Round(Double, MidpointRounding)
Math.Round(Decimal, Int32, MidpointRounding)Math.Round(Decimal, Int32, MidpointRounding)
Math.Round(Double, Int32, MidpointRounding)Math.Round(Double, Int32, MidpointRounding)

备注

本文中的 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。The C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

注解

本节内容:In this section:

我调用哪个方法?Which method do I call?

下表可用于选择适当的舍入方法。You can use the following table to select an appropriate rounding method. 除了Math.Round方法,它还包括Math.CeilingMath.FloorIn addition to the Math.Round methods, it also includes Math.Ceiling and Math.Floor.

功能To CallCall
数值舍入为整数使用舍入为最接近的约定。Round a number to an integer by using the rounding to nearest convention. Round(Decimal)

- 或 --or-

Round(Double)
舍入到通过使用指定的整数的数字舍入约定。Round a number to an integer by using a specified rounding convention. Round(Decimal, MidpointRounding)

- 或 --or-

Round(Double, MidpointRounding)
数值舍入到指定的小数位数使用舍入为最接近的约定。Round a number to a specified number of fractional digits by using the rounding to nearest convention. Round(Decimal, Int32)

- 或 --or-

Round(Double, Int32)
舍入到指定数目的通过使用指定的小数位数的数字舍入约定。Round a number to a specified number of fractional digits by using a specified rounding convention. Round(Decimal, Int32, MidpointRounding)

- 或 --or-

Round(Double, Int32, MidpointRounding)
RoundSingle到指定数目的通过使用指定舍入约定和最大程度减少丢失精度的小数位数的值。Round a Single value to a specified number of fractional digits by using a specified rounding convention and minimizing the loss of precision. 将转换SingleDecimal,并调用Round(Decimal, Int32, MidpointRounding)Convert the Single to a Decimal and call Round(Decimal, Int32, MidpointRounding).
数值舍入到指定的小数部分位数同时降到最低的中点值舍入精度的问题。Round a number to a specified number of fractional digits while minimizing problems of precision in rounding midpoint values. 调用实现"晚于或约等于"比较的舍入方法。Call a rounding method that implements a "greater than or approximately equal to" comparison. 请参阅舍入和精度See Rounding and precision.
将为一个整数,小数部分值舍入大于小数部分值。Round a fractional value to an integer that is greater than the fractional value. 例如,舍入 3.1 到 4。For example, round 3.1 to 4. Ceiling
将为一个整数,小数部分值舍入,小于的小数部分值。Round a fractional value to an integer that is less than the fractional value. 例如,舍入 3.9 到 3。For example, round 3.9 to 3. Floor

中点值和舍入的约定Midpoint values and rounding conventions

舍入涉及到将值指定的精度的数值转换为精度较低的最接近值。Rounding involves converting a numeric value with a specified precision to the nearest value with less precision. 例如,可以使用Round(Double)方法以 3.4 到 3.0 的数值进行舍入和Round(Double, Int32)方法要舍入到 3.58 3.579 的值。For example, you can use the Round(Double) method to round a value of 3.4 to 3.0, and the Round(Double, Int32) method to round a value of 3.579 to 3.58.

在一个中点值后结果中的最高有效位, 的值是两个数字之间准确地说的一半。In a midpoint value, the value after the least significant digit in the result is precisely half way between two numbers. 例如,3.47500 是一个中点值,如果要舍入两个小数位,而且 7.500 是一个中点值,如果要舍入为整数。For example, 3.47500 is a midpoint value if it is to be rounded two decimal places, and 7.500 is a midpoint value if it is to be rounded to an integer. 在这些情况下,最接近的值不能轻松地标识不舍入的约定。In these cases, the nearest value can't be easily identified without a rounding convention.

Round方法支持两种舍入的约定来处理中点值:The Round method supports two rounding conventions for handling midpoint values:

  • 远离零方向舍入Rounding away from zero

    中点值舍入为下一个编号从零开始。Midpoint values are rounded to the next number away from zero. 例如,3.75 将舍入到 3.8,3.85 将舍入到 3.9,-3.75 舍入到-3.8,和-3.85 舍入到-3.9。For example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8, and -3.85 rounds to -3.9. 这种形式的舍入由MidpointRounding.AwayFromZero枚举成员。This form of rounding is represented by the MidpointRounding.AwayFromZero enumeration member.

    远离零方向舍入为最广泛已知的形式的舍入。Rounding away from zero is the most widely known form of rounding.

  • 舍入为最接近,或银行家的舍入Rounding to nearest, or banker's rounding

    中点值舍入为最接近的偶数。Midpoint values are rounded to the nearest even number. 例如,3.75 和 3.85 舍入到 3.8,和-3.75 和-3.85 舍入到-3.8。For example, both 3.75 and 3.85 round to 3.8, and both -3.75 and -3.85 round to -3.8. 这种形式的舍入由MidpointRounding.ToEven枚举成员。This form of rounding is represented by the MidpointRounding.ToEven enumeration member.

    舍入为最接近是标准形式的舍入在财务和统计操作中使用。Rounding to nearest is the standard form of rounding used in financial and statistical operations. 它符合 IEEE 标准 754,第 4 节。It conforms to IEEE Standard 754, section 4. 多个舍入操作中使用时,它减少了通过一致地在单方向的中点值舍入导致的舍入错误。When used in multiple rounding operations, it reduces the rounding error that is caused by consistently rounding midpoint values in a single direction. 在某些情况下,此舍入错误非常显著。In some cases, this rounding error can be significant.

    下面的示例说明了可能会导致持续舍入的一个方向的中点值的偏差。The following example illustrates the bias that can result from consistently rounding midpoint values in a single direction. 该示例计算的数组,则返回 true 平均数Decimal值,并当数组中的值将舍入使用的两个约定时,然后计算平均值。The example computes the true mean of an array of Decimal values, and then computes the mean when the values in the array are rounded by using the two conventions. 在此示例中,则返回 true 的平均偏差和结果时舍入为最接近平均值是相同的。In this example, the true mean and the mean that results when rounding to nearest are the same. 但是,当远离零方向舍入结果的平均值不同.05 (或 3.6%)从 true 的平均值。However, the mean that results when rounding away from zero differs by .05 (or by 3.6%) from the true mean.

    decimal[] values = { 1.15m, 1.25m, 1.35m, 1.45m, 1.55m, 1.65m };
    decimal sum = 0;
    
    // Calculate true mean.
    foreach (var value in values)
       sum += value;
    
    Console.WriteLine("True mean:     {0:N2}", sum/values.Length);
    
    // Calculate mean with rounding away from zero.
    sum = 0;
    foreach (var value in values)
       sum += Math.Round(value, 1, MidpointRounding.AwayFromZero);
    
    Console.WriteLine("AwayFromZero:  {0:N2}", sum/values.Length);
    
    // Calculate mean with rounding to nearest.
    sum = 0;
    foreach (var value in values)
       sum += Math.Round(value, 1, MidpointRounding.ToEven);
    
    Console.WriteLine("ToEven:        {0:N2}", sum/values.Length);
    // The example displays the following output:
    //       True mean:     1.40
    //       AwayFromZero:  1.45
    //       ToEven:        1.40
    
    Module Example
       Public Sub Main()
          Dim values() As Decimal = { 1.15d, 1.25d, 1.35d, 1.45d, 1.55d, 1.65d }
          Dim sum As Decimal
          
          ' Calculate true mean.
          For Each value In values
             sum += value
          Next
          Console.WriteLine("True mean:     {0:N2}", sum/values.Length)
          
          ' Calculate mean with rounding away from zero.
          sum = 0
          For Each value In values
             sum += Math.Round(value, 1, MidpointRounding.AwayFromZero)
          Next
          Console.WriteLine("AwayFromZero:  {0:N2}", sum/values.Length)
          
          ' Calculate mean with rounding to nearest.
          sum = 0
          For Each value In values
             sum += Math.Round(value, 1, MidpointRounding.ToEven)
          Next
          Console.WriteLine("ToEven:        {0:N2}", sum/values.Length)
       End Sub
    End Module
    ' The example displays the following output:
    '       True mean:     1.40
    '       AwayFromZero:  1.45
    '       ToEven:        1.40
    

默认情况下,Round方法使用舍入为最接近的约定。By default, the Round method uses the rounding to nearest convention. 下表列出了的重载Round方法,并舍入的约定,每个使用。The following table lists the overloads of the Round method and the rounding convention that each uses.

重载Overload 舍入约定Rounding convention
Round(Decimal) ToEven
Round(Double) ToEven
Round(Decimal, Int32) ToEven
Round(Double, Int32) ToEven
Round(Decimal, MidpointRounding) mode参数。Determined by mode parameter.
Round(Double, MidpointRounding) mode参数Determined by mode parameter
Round(Decimal, Int32, MidpointRounding) mode参数Determined by mode parameter
Round(Double, Int32, MidpointRounding) mode参数Determined by mode parameter

舍入和精度Rounding and precision

若要确定舍入运算是否涉及一个中点值,Round方法将原始值与要舍入 10 相乘n,其中n是所需的小数部分数返回值中的数字,然后确定剩余的小数部分的值是否大于或等于.5。In order to determine whether a rounding operation involves a midpoint value, the Round method multiplies the original value to be rounded by 10n, where n is the desired number of fractional digits in the return value, and then determines whether the remaining fractional portion of the value is greater than or equal to .5. 这是在"测试相等"部分中的测试是否相等,并按论述的方式稍有变化Double参考主题,具有浮点值是否相等的测试存在问题由于浮点格式的问题与二进制文件表示形式和精度。This is a slight variation on a test for equality, and as discussed in the "Testing for Equality" section of the Double reference topic, tests for equality with floating-point values are problematic because of the floating-point format's issues with binary representation and precision. 这意味着,任何略小于.5 (由于精度损失) 的数字的小数部分将不会舍入上升。This means that any fractional portion of a number that is slightly less than .5 (because of a loss of precision) will not be rounded upward.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

以下示例演示了该问题。The following example illustrates the problem. 重复添加.1 为 11.0,并将舍入到最接近的整数结果。It repeatedly adds .1 to 11.0 and rounds the result to the nearest integer. 舍入的约定,不管 11.5 应舍入到 12。Regardless of the rounding convention, 11.5 should round to 12. 但是,如中的示例所示的输出,事实并非如此。However, as the output from the example shows, it does not. 该示例使用"R"标准数字格式字符串要显示的浮点值的完全精度,并显示要舍入的值在重复添加内容,期间失去精度和其值实际是11.499999999999998。The example uses the "R" standard numeric format string to display the floating point value's full precision, and shows that the value to be rounded has lost precision during repeated additions, and its value is actually 11.499999999999998. 因为.499999999999998 小于.5,值不进行舍入为下一步的最大整数。Because .499999999999998 is less than .5, the value is not rounded to the next highest integer. 如该示例还表明,如果我们只需向其分配常量值 11.5 不会出现此问题Double变量。As the example also shows, this problem does not occur if we simply assign the constant value 11.5 to a Double variable.

using System;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n", 
                        "Value", "Full Precision", "ToEven",
                        "AwayFromZero");
      double value = 11.1;
      for (int ctr = 0; ctr <= 5; ctr++)    
         value = RoundValueAndAdd(value);

      Console.WriteLine();

      value = 11.5;
      RoundValueAndAdd(value);
   }
   
   private static double RoundValueAndAdd(double value)
   {
      Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                        value, Math.Round(value, MidpointRounding.ToEven),
                        Math.Round(value, MidpointRounding.AwayFromZero));
      return value + .1;
   }
}
// The example displays the following output:
//       Value       Full Precision        ToEven    AwayFromZero
//       
//        11.1                 11.1            11              11
//        11.2                 11.2            11              11
//        11.3   11.299999999999999            11              11
//        11.4   11.399999999999999            11              11
//        11.5   11.499999999999998            11              11
//        11.6   11.599999999999998            12              12
//       
//        11.5                 11.5            12              12
Module Example
   Public Sub Main()
      Dim value As Double = 11.1

      Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}", 
                        "Value", "Full Precision", "ToEven",
                        "AwayFromZero")
      Console.WriteLine()
      For ctr As Integer = 0 To 5    
         value = RoundValueAndAdd(value)
      Next
      Console.WriteLine()

      value = 11.5
      RoundValueAndAdd(value)
   End Sub
   
   Private Function RoundValueAndAdd(value As Double) As Double
      Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                        value, Math.Round(value, MidpointRounding.ToEven),
                        Math.Round(value, MidpointRounding.AwayFromZero))
      Return value + .1
   End Function   
End Module
' The example displays the following output:
'       Value       Full Precision        ToEven    AwayFromZero
'       
'        11.1                 11.1            11              11
'        11.2                 11.2            11              11
'        11.3   11.299999999999999            11              11
'        11.4   11.399999999999999            11              11
'        11.5   11.499999999999998            11              11
'        11.6   11.599999999999998            12              12
'       
'        11.5                 11.5            12              12

问题中舍入中点值是精度的最有可能会出现在下列情况:Problems of precision in rounding midpoint values are most likely to arise in the following conditions:

  • 当不能准确地说以浮点类型的二进制格式表示的小数部分值。When a fractional value cannot be expressed precisely in the floating-point type's binary format.

  • 当要舍入的值会计算从一个或多个浮点运算。When the value to be rounded is calculated from one or more floating-point operations.

  • 当要舍入的值是Single而非DoubleDecimalWhen the value to be rounded is a Single rather than a Double or Decimal. 有关详细信息,请参阅下一部分中,舍入和单精度浮点值For more information, see the next section, Rounding and single-precision floating-point values.

在缺乏精确地进行舍入操作有问题的情况下,可以执行以下操作:In cases where the lack of precision in rounding operations is problematic, you can do the following:

  • 如果舍入运算调用的重载,将舍入Double值,您可以更改DoubleDecimal值,并调用重载的舍入Decimal相反值。If the rounding operation calls an overload that rounds a Double value, you can change the Double to a Decimal value and call an overload that rounds a Decimal value instead. 尽管Decimal数据类型还具有精度损失和表示形式的问题,这些问题都得不太常见。Although the Decimal data type also has problems of representation and loss of precision, these issues are far less common.

  • 定义自定义的舍入算法来执行"几乎 equal"的测试,以确定是否要舍入的值为接受接近中点值。Define a custom rounding algorithm that performs a "nearly equal" test to determine whether the value to be rounded is acceptably close to a midpoint value. 下面的示例定义RoundApproximate检查小数部分值是否足够接近要受到舍入中点的中点值的方法。The following example defines a RoundApproximate method that examines whether a fractional value is sufficiently near to a midpoint value to be subject to midpoint rounding. 如示例输出所示,它可以解决在前面的示例所示舍入问题。As the output from the example shows, it corrects the rounding problem shown in the previous example.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n", 
                            "Value", "Full Precision", "ToEven",
                            "AwayFromZero");
          double value = 11.1;
          for (int ctr = 0; ctr <= 5; ctr++)    
             value = RoundValueAndAdd(value);
    
          Console.WriteLine();
    
          value = 11.5;
          RoundValueAndAdd(value);
       }
       
       private static double RoundValueAndAdd(double value)
       {
          const double tolerance = 8e-14;
    
          Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                            value, 
                            RoundApproximate(value, 0, tolerance, MidpointRounding.ToEven),
                            RoundApproximate(value, 0, tolerance, MidpointRounding.AwayFromZero));
          return value + .1;
       }
    
       private static double RoundApproximate(double dbl, int digits, double margin, 
                                         MidpointRounding mode)
       {                                      
          double fraction = dbl * Math.Pow(10, digits);
          double value = Math.Truncate(fraction); 
          fraction = fraction - value;   
          if (fraction == 0)
             return dbl;
          
          double tolerance = margin * dbl;
          // Determine whether this is a midpoint value.
          if ((fraction >= .5 - tolerance) & (fraction <= .5 + tolerance)) {
             if (mode == MidpointRounding.AwayFromZero)
                return (value + 1)/Math.Pow(10, digits);
             else
                if (value % 2 != 0)
                   return (value + 1)/Math.Pow(10, digits);
                else
                   return value/Math.Pow(10, digits);
          }
          // Any remaining fractional value greater than .5 is not a midpoint value.
          if (fraction > .5)
             return (value + 1)/Math.Pow(10, digits);
          else
             return value/Math.Pow(10, digits);
       }
    }
    // The example displays the following output:
    //       Value       Full Precision        ToEven    AwayFromZero
    //       
    //        11.1                 11.1            11              11
    //        11.2                 11.2            11              11
    //        11.3   11.299999999999999            11              11
    //        11.4   11.399999999999999            11              11
    //        11.5   11.499999999999998            12              12
    //        11.6   11.599999999999998            12              12
    //       
    //        11.5                 11.5            12              12
    
    Module Example
       Public Sub Main()
          Dim value As Double = 11.1
    
          Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n", 
                            "Value", "Full Precision", "ToEven",
                            "AwayFromZero")
          For ctr As Integer = 0 To 5    
             value = RoundValueAndAdd(value)
          Next
          Console.WriteLine()
    
          value = 11.5
          RoundValueAndAdd(value)
       End Sub
       
       Private Function RoundValueAndAdd(value As Double) As Double
          Const tolerance As Double = 8e-14
          Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                            value, 
                            RoundApproximate(value, 0, tolerance, MidpointRounding.ToEven),
                            RoundApproximate(value, 0, tolerance, MidpointRounding.AwayFromZero))
          Return value + .1
       End Function   
    
       Private Function RoundApproximate(dbl As Double, digits As Integer, margin As Double, 
                                         mode As MidpointRounding) As Double
          Dim fraction As Double = dbl * Math.Pow(10, digits)
          Dim value As Double = Math.Truncate(fraction) 
          fraction = fraction - value   
          If fraction = 0 Then Return dbl
          
          Dim tolerance As Double = margin * dbl
          ' Determine whether this is a midpoint value.
          If (fraction >= .5 - tolerance) And (fraction <= .5 + tolerance) Then
             If mode = MidpointRounding.AwayFromZero Then
                Return (value + 1)/Math.Pow(10, digits)
             Else
                If value Mod 2 <> 0 Then
                   Return (value + 1)/Math.Pow(10, digits)
                Else
                   Return value/Math.Pow(10, digits)
                End If
             End If
          End If
          ' Any remaining fractional value greater than .5 is not a midpoint value.
          If fraction > .5 Then
             Return (value + 1)/Math.Pow(10, digits)
          Else
             return value/Math.Pow(10, digits)
          End If      
       End Function
    End Module
    ' The example displays the following output:
    '       Value       Full Precision        ToEven    AwayFromZero
    '       
    '        11.1                 11.1            11              11
    '        11.2                 11.2            11              11
    '        11.3   11.299999999999999            11              11
    '        11.4   11.399999999999999            11              11
    '        11.5   11.499999999999998            12              12
    '        11.6   11.599999999999998            12              12
    '       
    '        11.5                 11.5            12              12
    

舍入和单精度浮点值Rounding and single-precision floating-point values

Round方法包含接受的类型参数的重载DecimalDoubleThe Round method includes overloads that accept arguments of type Decimal and Double. 舍入值的类型没有方法SingleThere are no methods that round values of type Single. 如果传递Single值的重载之一Round方法,它是强制转换 (在 C#) 或 (在 Visual Basic) 转换成Double,和相应Round重载,并Double调用参数。If you pass a Single value to one of the overloads of the Round method, it is cast (in C#) or converted (in Visual Basic) to a Double, and the corresponding Round overload with a Double parameter is called. 虽然这是一个扩大转换,但它通常涉及到丢失精度,如以下示例所示。Although this is a widening conversion, it often involves a loss of precision, as the following example illustrates. Single16.325 值传递给Round方法和舍入为两个小数位使用舍入为最接近的约定,结果是 16.32 16.33 和非预期结果。When a Single value of 16.325 is passed to the Round method and rounded to two decimal places using the rounding to nearest convention, the result is 16.33 and not the expected result of 16.32.

using System;

public class Example
{
   public static void Main()
   {
      Single value = 16.325f;
      Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", 
                        value, value.GetType().Name, (double) value, 
                        ((double) (value)).GetType().Name);
      Console.WriteLine(Math.Round(value, 2));
      Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero));
      Console.WriteLine();
      
      Decimal decValue = (decimal) value;
      Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ", 
                        value, value.GetType().Name, decValue, 
                        decValue.GetType().Name);
      Console.WriteLine(Math.Round(decValue, 2));
      Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero));
   }
}
// The example displays the following output:
//    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
//    16.33
//    16.33
//    
//    Cast of 16.325 (type Single) to 16.325 (type Decimal):
//    16.32
//    16.33
Module Example
   Public Sub Main()
      Dim value As Single = 16.325
      Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", 
                        value, value.GetType().Name, CDbl(value), 
                        CDbl(value).GetType().Name)
      Console.WriteLine(Math.Round(value, 2))
      Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero))
      Console.WriteLine()
      
      Dim decValue As Decimal = CDec(value)
      Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ", 
                        value, value.GetType().Name, decValue, 
                        decValue.GetType().Name)
      Console.WriteLine(Math.Round(decValue, 2))
      Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero))
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
'    16.33
'    16.33
'    
'    Cast of 16.325 (type Single) to 16.325 (type Decimal):
'    16.32
'    16.33

此意外的结果是导致精度的转换中丢失Single值设为DoubleThis unexpected result is due to a loss of precision in the conversion of the Single value to a Double. 因为得到Double16.325000762939453 的值不是一个中点值且大于 16.325、 始终向上四舍五入。Because the resulting Double value of 16.325000762939453 is not a midpoint value and is greater than 16.325, it is always rounded upward.

在许多情况下,如示例所示,精度损失可以最小化或消除转换或转换Single值设为DecimalIn many cases, as the example illustrates, the loss of precision can be minimized or eliminated by casting or converting the Single value to a Decimal. 请注意,由于这是收缩转换,它需要使用转换运算符或调用转换方法。Note that, because this is a narrowing conversion, it requires using a cast operator or calling a conversion method.

##

Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding)

将小数值舍入到指定数量的小数位,并为中点值使用指定的舍入规则。Rounds a decimal value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

public:
 static System::Decimal Round(System::Decimal d, int decimals, MidpointRounding mode);
public static decimal Round (decimal d, int decimals, MidpointRounding mode);
static member Round : decimal * int * MidpointRounding -> decimal
Public Shared Function Round (d As Decimal, decimals As Integer, mode As MidpointRounding) As Decimal

参数

d
Decimal Decimal Decimal Decimal

要舍入的小数。A decimal number to be rounded.

decimals
Int32 Int32 Int32 Int32

返回值中的小数位数。The number of decimal places in the return value.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

在两个数字之间时如何舍入 d 的规范。Specification for how to round d if it is midway between two other numbers.

返回

最接近 ddecimals 位小数的数字。The number nearest to d that contains a number of fractional digits equal to decimals. 如果 ddecimals 少部分数字,d 原样返回。If d has fewer fractional digits than decimals, d is returned unchanged.

异常

decimals 小于 0 或大于 28。decimals is less than 0 or greater than 28.

mode 不是 MidpointRounding 的一个有效值。mode is not a valid value of MidpointRounding.

结果超出了 Decimal 的范围。The result is outside the range of a Decimal.

注解

请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

decimals自变量的范围可以介于 0 到 28。The value of the decimals argument can range from 0 to 28.

示例Example

下面的示例演示如何使用Round方法替换MidpointRounding枚举。The following example demonstrates how to use the Round method with the MidpointRounding enumeration.

// This example demonstrates the Math.Round() method in conjunction 
// with the MidpointRounding enumeration.
using namespace System;

void main()
{
    Decimal result = (Decimal) 0.0;
    Decimal posValue = (Decimal) 3.45;
    Decimal negValue = (Decimal) -3.45;

    // By default, round a positive and a negative value to the nearest
    // even number. The precision of the result is 1 decimal place.
    result = Math::Round(posValue, 1);
    Console::WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue);
    result = Math::Round(negValue, 1);
    Console::WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue);
    Console::WriteLine();

    // Round a positive value to the nearest even number, then to the
    // nearest number away from zero. The precision of the result is 1
    // decimal place.
    result = Math::Round(posValue, 1, MidpointRounding::ToEven);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
        result, posValue);
    result = Math::Round(posValue, 1, MidpointRounding::AwayFromZero);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
        result, posValue);
    Console::WriteLine();

    // Round a negative value to the nearest even number, then to the
    // nearest number away from zero. The precision of the result is 1
    // decimal place.
    result = Math::Round(negValue, 1, MidpointRounding::ToEven);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
        result, negValue);
    result = Math::Round(negValue, 1, MidpointRounding::AwayFromZero);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
        result, negValue);
    Console::WriteLine();
}

/*
This code example produces the following results:

3.4 = Math.Round( 3.45, 1)
-3.4 = Math.Round(-3.45, 1)

3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)

-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)

*/
decimal result = 0.0m;
decimal posValue =  3.45m;
decimal negValue = -3.45m;

// By default, round a positive and a negative value to the nearest even number. 
// The precision of the result is 1 decimal place.

result = Math.Round(posValue, 1);
Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue);
result = Math.Round(negValue, 1);
Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue);
Console.WriteLine();

// Round a positive value to the nearest even number, then to the nearest number away from zero. 
// The precision of the result is 1 decimal place.

result = Math.Round(posValue, 1, MidpointRounding.ToEven);
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", result, posValue);
result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero);
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", result, posValue);
Console.WriteLine();

// Round a negative value to the nearest even number, then to the nearest number away from zero. 
// The precision of the result is 1 decimal place.

result = Math.Round(negValue, 1, MidpointRounding.ToEven);
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", result, negValue);
result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero);
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", result, negValue);
Console.WriteLine();
/*
This code example produces the following results:

3.4 = Math.Round( 3.45, 1)
-3.4 = Math.Round(-3.45, 1)

3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)

-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)

*/
' This example demonstrates the Math.Round() method in conjunction 
' with the MidpointRounding enumeration.
Imports System

Class Sample
    Public Shared Sub Main() 
        Dim result As Decimal = 0D
        Dim posValue As Decimal = 3.45D
        Dim negValue As Decimal = -3.45D
        
        ' By default, round a positive and a negative value to the nearest even number. 
        ' The precision of the result is 1 decimal place.
        result = Math.Round(posValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue)
        result = Math.Round(negValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue)
        Console.WriteLine()
        
        ' Round a positive value to the nearest even number, then to the nearest number 
        ' away from zero. The precision of the result is 1 decimal place.
        result = Math.Round(posValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", _
                           result, posValue)
        result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", _
                           result, posValue)
        Console.WriteLine()
        
        ' Round a negative value to the nearest even number, then to the nearest number 
        ' away from zero. The precision of the result is 1 decimal place.
        result = Math.Round(negValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", _
                            result, negValue)
        result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", _
                           result, negValue)
        Console.WriteLine()
    
    End Sub 'Main
End Class 'Sample
'
'This code example produces the following results:
'
' 3.4 = Math.Round( 3.45, 1)
'-3.4 = Math.Round(-3.45, 1)
'
' 3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
' 3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
'
'-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
'-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
'
另请参阅

Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding)

将双精度浮点值舍入到指定数量的小数位,并为中点值使用指定的舍入规则。Rounds a double-precision floating-point value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

public:
 static double Round(double value, int digits, MidpointRounding mode);
public static double Round (double value, int digits, MidpointRounding mode);
static member Round : double * int * MidpointRounding -> double
Public Shared Function Round (value As Double, digits As Integer, mode As MidpointRounding) As Double

参数

value
Double Double Double Double

要舍入的双精度浮点数。A double-precision floating-point number to be rounded.

digits
Int32 Int32 Int32 Int32

返回值中的小数数字。The number of fractional digits in the return value.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

在两个数字之间时如何舍入 value 的规范。Specification for how to round value if it is midway between two other numbers.

返回

最接近 valuedigits 位小数的数字。The number nearest to value that has a number of fractional digits equal to digits. 如果 valuedigits 少部分数字,value 原样返回。If value has fewer fractional digits than digits, value is returned unchanged.

异常

digits 小于 0 或大于 15。digits is less than 0 or greater than 15.

mode 不是 MidpointRounding 的一个有效值。mode is not a valid value of MidpointRounding.

注解

digits自变量的范围可以介于 0 到 15。The value of the digits argument can range from 0 to 15. 请注意,15 是支持的整数和小数位数的最大数目Double类型。Note that 15 is the maximum number of integral and fractional digits supported by the Double type.

请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

如果的值value自变量是Double.NaN,该方法将返回Double.NaNIf the value of the value argument is Double.NaN, the method returns Double.NaN. 如果valueDouble.PositiveInfinityDouble.NegativeInfinity,该方法将返回Double.PositiveInfinityDouble.NegativeInfinity分别。If value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

示例Example

下面的示例演示如何使用Round(Double, Int32, MidpointRounding)方法替换MidpointRounding枚举。The following example demonstrates how to use the Round(Double, Int32, MidpointRounding) method with the MidpointRounding enumeration.

 double posValue =  3.45;
 double negValue = -3.45;

 // Round a positive and a negative value using the default. 
 double result = Math.Round(posValue, 1);
 Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue);
 result = Math.Round(negValue, 1);
 Console.WriteLine("{0,4} = Math.Round({1,5}, 1)\n", result, negValue);

 // Round a positive value using a MidpointRounding value. 
 result = Math.Round(posValue, 1, MidpointRounding.ToEven);
 Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                   result, posValue);
 result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero);
 Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)\n", 
                   result, posValue);

 // Round a negative value using a MidpointRounding value. 
 result = Math.Round(negValue, 1, MidpointRounding.ToEven);
 Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                   result, negValue);
 result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero);
 Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)\n", 
                   result, negValue);
// The example displays the following output:
//        3.4 = Math.Round( 3.45, 1)
//       -3.4 = Math.Round(-3.45, 1)
//       
//        3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
//        3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
//       
//       -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
//       -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
Module Example
    Public Sub Main() 
        Dim posValue As Double = 3.45
        Dim negValue As Double = -3.45
        
        ' Round a positive and a negative value using the default.  
        Dim result As Double = Math.Round(posValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue)
        result = Math.Round(negValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue)
        Console.WriteLine()
        
        ' Round a positive value using a MidpointRounding value. 
        result = Math.Round(posValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                           result, posValue)
        result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", 
                           result, posValue)
        Console.WriteLine()
        
        ' Round a positive value using a MidpointRounding value. 
        result = Math.Round(negValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                            result, negValue)
        result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", 
                           result, negValue)
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'       3.4 = Math.Round( 3.45, 1)
'       -3.4 = Math.Round(-3.45, 1)
'       
'       3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
'       3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
'       
'       -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
'       -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)

调用方说明

由于表示十进制值为浮点数,或在某些情况下执行浮点值的算术运算可能会导致精度丢失Round(Double, Int32, MidpointRounding)方法可能不会显示要舍入为指定的中点值通过mode参数。Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter. 下面的示例,其中 2.135 将舍入到而不是 2.14 2.13 所示。This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. 这是因为该方法将在内部相乘value10数字,和乘法运算在这种情况下会精度损失。This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

[!code-csharpSystem.Math.Round#3] [!code-vbSystem.Math.Round#3][!code-csharpSystem.Math.Round#3] [!code-vbSystem.Math.Round#3]

另请参阅

Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding)

将双精度浮点值舍入到最接近的整数,并为中点值使用指定的舍入约定。Rounds a double-precision floating-point value to the nearest integer, and uses the specified rounding convention for midpoint values.

public:
 static double Round(double value, MidpointRounding mode);
public static double Round (double value, MidpointRounding mode);
static member Round : double * MidpointRounding -> double
Public Shared Function Round (value As Double, mode As MidpointRounding) As Double

参数

value
Double Double Double Double

要舍入的双精度浮点数。A double-precision floating-point number to be rounded.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

在两个数字之间时如何舍入 value 的规范。Specification for how to round value if it is midway between two other numbers.

返回

最接近 value 的整数。The integer nearest value. 如果 value 是两个整数的中值,这两个整数一个为偶数,另一个为奇数,则 mode 确定返回两个整数中的哪一个。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. 请注意,此方法返回 Double,而不是整数类型。Note that this method returns a Double instead of an integral type.

异常

mode 不是 MidpointRounding 的一个有效值。mode is not a valid value of MidpointRounding.

注解

请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

如果的值value自变量是Double.NaN,该方法将返回Double.NaNIf the value of the value argument is Double.NaN, the method returns Double.NaN. 如果valueDouble.PositiveInfinityDouble.NegativeInfinity,该方法将返回Double.PositiveInfinityDouble.NegativeInfinity分别。If value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

示例Example

下面的示例显示返回的值Round(Double)方法,Round(Double, MidpointRounding)方法替换mode自变量ToEven,和Round(Double, MidpointRounding)方法替换mode自变量的AwayFromZeroThe following example displays values returned by the Round(Double) method, the Round(Double, MidpointRounding) method with a mode argument of ToEven, and the Round(Double, MidpointRounding) method with a mode argument of AwayFromZero.

using System;

public class Example
{
   public static void Main()
   {
      Double[] values = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 
                          12.7, 12.8, 12.9, 13.0 };
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero");
      foreach (var value in values)
         Console.WriteLine("{0,-10:R} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero));
   }
}
// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero
//       12         12         12         12
//       12.1       12         12         12
//       12.2       12         12         12
//       12.3       12         12         12
//       12.4       12         12         12
//       12.5       12         12         13
//       12.6       13         13         13
//       12.7       13         13         13
//       12.8       13         13         13
//       12.9       13         13         13
//       13.0       13         13         13
Module Example
   Public Sub Main()
      Dim values() As Double = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 
                                 12.7, 12.8, 12.9, 13.0 }
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero")
      For Each value In values
         Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero))
      Next
   End Sub
End Module
' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero
'       12         12         12         12
'       12.1       12         12         12
'       12.2       12         12         12
'       12.3       12         12         12
'       12.4       12         12         12
'       12.5       12         12         13
'       12.6       13         13         13
'       12.7       13         13         13
'       12.8       13         13         13
'       12.9       13         13         13
'       13.0       13         13         13

调用方说明

由于表示十进制值为浮点数,或在某些情况下执行浮点值的算术运算可能会导致精度丢失Round(Double, MidpointRounding)方法可能不会显示要舍入到中点值接近的偶数。Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, MidpointRounding) method may not appear to round midpoint values to the nearest even integer. 在以下示例中,因为浮点值.1 有没有有限的二进制表示形式的首次调用到Round(Double)11.5 值的方法将返回而不是 12 11。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.

[!code-csharp-interactiveSystem.Math.Round#4] [!code-vbSystem.Math.Round#4][!code-csharp-interactiveSystem.Math.Round#4] [!code-vbSystem.Math.Round#4]

另请参阅

Round(Double, Int32) Round(Double, Int32) Round(Double, Int32) Round(Double, Int32)

将双精度浮点值舍入到指定数量的小数位,并将中点值舍入到最接近的偶数。Rounds a double-precision floating-point value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

public:
 static double Round(double value, int digits);
public static double Round (double value, int digits);
static member Round : double * int -> double
Public Shared Function Round (value As Double, digits As Integer) As Double

参数

value
Double Double Double Double

要舍入的双精度浮点数。A double-precision floating-point number to be rounded.

digits
Int32 Int32 Int32 Int32

返回值中的小数数字。The number of fractional digits in the return value.

返回

最接近 valuedigits 位小数的数字。The number nearest to value that contains a number of fractional digits equal to digits.

异常

digits 小于 0 或大于 15。digits is less than 0 or greater than 15.

注解

digits自变量的范围可以介于 0 到 15。The value of the digits argument can range from 0 to 15. 请注意,15 是支持的整数和小数位数的最大数目Double类型。Note that 15 is the maximum number of integral and fractional digits supported by the Double type.

此方法使用的默认舍入的约定MidpointRounding.ToEvenThis method uses the default rounding convention of MidpointRounding.ToEven. 请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

如果的值value自变量是Double.NaN,该方法将返回Double.NaNIf the value of the value argument is Double.NaN, the method returns Double.NaN. 如果valueDouble.PositiveInfinityDouble.NegativeInfinity,该方法将返回Double.PositiveInfinityDouble.NegativeInfinity分别。If value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

示例Example

下面的示例将舍入到具有小数部分位数的双精度数的两个小数位数与双精度值。The following example rounds double values with two fractional digits to doubles that have a single fractional digit.

Math::Round(3.44, 1); //Returns 3.4.
Math::Round(3.45, 1); //Returns 3.4.
Math::Round(3.46, 1); //Returns 3.5.

Math::Round(4.34, 1); // Returns 4.3
Math::Round(4.35, 1); // Returns 4.4
Math::Round(4.36, 1); // Returns 4.4
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.

Math.Round(4.34, 1); // Returns 4.3
Math.Round(4.35, 1); // Returns 4.4
Math.Round(4.36, 1); // Returns 4.4
Math.Round(3.44, 1) 'Returns 3.4.
Math.Round(3.45, 1) 'Returns 3.4.
Math.Round(3.46, 1) 'Returns 3.5.

Math.Round(4.34, 1) ' Returns 4.3
Math.Round(4.35, 1) ' Returns 4.4
Math.Round(4.36, 1) ' Returns 4.4

调用方说明

由于表示十进制值为浮点数,或在某些情况下执行浮点值的算术运算可能会导致精度丢失Round(Double, Int32)方法可能不会显示要舍入到中点值最近的偶数值中digits小数位置。Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32) method may not appear to round midpoint values to the nearest even value in the digits decimal position. 下面的示例,其中 2.135 将舍入到而不是 2.14 2.13 所示。This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. 这是因为该方法将在内部相乘value10数字,和乘法运算在这种情况下会精度损失。This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

[!code-csharp-interactiveSystem.Math.Round#2] [!code-vbSystem.Math.Round#2][!code-csharp-interactiveSystem.Math.Round#2] [!code-vbSystem.Math.Round#2]

另请参阅

Round(Double) Round(Double) Round(Double) Round(Double)

将双精度浮点值舍入到最接近的整数值,并将中点值舍入到最接近的偶数。Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.

public:
 static double Round(double a);
public static double Round (double a);
static member Round : double -> double
Public Shared Function Round (a As Double) As Double

参数

a
Double Double Double Double

要舍入的双精度浮点数。A double-precision floating-point number to be rounded.

返回

最接近 a 的整数。The integer nearest a. 如果 a 的小数部分正好处于两个整数中间,其中一个整数为偶数,另一个整数为奇数,则返回偶数。If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned. 请注意,此方法返回 Double,而不是整数类型。Note that this method returns a Double instead of an integral type.

注解

此方法使用的默认舍入的约定MidpointRounding.ToEvenThis method uses the default rounding convention of MidpointRounding.ToEven. 请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

如果的值a自变量是Double.NaN,该方法将返回Double.NaNIf the value of the a argument is Double.NaN, the method returns Double.NaN. 如果aDouble.PositiveInfinityDouble.NegativeInfinity,该方法将返回Double.PositiveInfinityDouble.NegativeInfinity分别。If a is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

从 Visual Basic 15.8 开始,双到整数的转换的性能如果返回的值传递优化Round方法的任何整型的转换函数,或者如果的双精度值返回的Round自动转换为一个整数,其Option Strict设置为 Off。Starting with Visual Basic 15.8, the performance of Double-to-integer conversion is optimized if you pass the value returned by the Round method to the any of the integral conversion functions, or if the Double value returned by Round is automatically converted to an integer with Option Strict set to Off. 此优化使代码可以更快运行 -- 对于进行大量到整型类型的转换的代码,可快达两倍。This optimization allows code to run faster -- up to twice as fast for code that does a large number of conversions to integer types. 下面的示例演示了这种优化的转换:The following example illustrates such optimized conversions:

Dim d1 As Double = 1043.75133
Dim i1 As Integer = CInt(Math.Ceiling(d1))        ' Result: 1044

Dim d2 As Double = 7968.4136
Dim i2 As Integer = CInt(Math.Ceiling(d2))        ' Result: 7968

示例Example

下面的示例演示了舍入为最接近的整数值。The following example demonstrates rounding to the nearest integer value.

using namespace System;

void main()
{
    Console::WriteLine("Classic Math.Round in CPP");
    Console::WriteLine(Math::Round(4.4));     // 4
    Console::WriteLine(Math::Round(4.5));     // 4
    Console::WriteLine(Math::Round(4.6));     // 5
    Console::WriteLine(Math::Round(5.5));     // 6
}
Console.WriteLine("Classic Math.Round in CSharp");
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
Imports System

Module Module1

    Sub Main()
    Console.WriteLine("Classic Math.Round in Visual Basic")
    Console.WriteLine(Math.Round(4.4)) ' 4
    Console.WriteLine(Math.Round(4.5)) ' 4
    Console.WriteLine(Math.Round(4.6)) ' 5
    Console.WriteLine(Math.Round(5.5)) ' 6
    End Sub

End Module

调用方说明

由于表示十进制值为浮点数,或在某些情况下执行浮点值的算术运算可能会导致精度丢失Round(Double)方法可能不会显示要舍入到中点值接近的偶数。Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double) method may not appear to round midpoint values to the nearest even integer. 在以下示例中,因为浮点值.1 有没有有限的二进制表示形式的首次调用到Round(Double)11.5 值的方法将返回而不是 12 11。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.

[!code-csharpSystem.Math.Round#1] [!code-vbSystem.Math.Round#1][!code-csharpSystem.Math.Round#1] [!code-vbSystem.Math.Round#1]

另请参阅

Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32)

将小数值舍入到指定数量的小数位,并将中点值舍入到最接近的偶数。Rounds a decimal value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

public:
 static System::Decimal Round(System::Decimal d, int decimals);
public static decimal Round (decimal d, int decimals);
static member Round : decimal * int -> decimal
Public Shared Function Round (d As Decimal, decimals As Integer) As Decimal

参数

d
Decimal Decimal Decimal Decimal

要舍入的小数。A decimal number to be rounded.

decimals
Int32 Int32 Int32 Int32

返回值中的小数位数。The number of decimal places in the return value.

返回

最接近 ddecimals 位小数的数字。The number nearest to d that contains a number of fractional digits equal to decimals.

异常

decimals 小于 0 或大于 28。decimals is less than 0 or greater than 28.

结果超出了 Decimal 的范围。The result is outside the range of a Decimal.

注解

decimals自变量的范围可以介于 0 到 28。The value of the decimals argument can range from 0 to 28.

此方法使用的默认舍入的约定MidpointRounding.ToEvenThis method uses the default rounding convention of MidpointRounding.ToEven. 请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

示例Example

下面的示例将舍入小数值,并且两个小数位到具有小数部分位数的值。The following example rounds decimal values with two fractional digits to values that have a single fractional digit.

Console.WriteLine(Math.Round(3.44m, 1)); 
Console.WriteLine(Math.Round(3.45m, 1)); 
Console.WriteLine(Math.Round(3.46m, 1)); 
Console.WriteLine();

Console.WriteLine(Math.Round(4.34m, 1)); 
Console.WriteLine(Math.Round(4.35m, 1)); 
Console.WriteLine(Math.Round(4.36m, 1)); 
// The example displays the following output:
//       3.4
//       3.4
//       3.5
//       
//       4.3
//       4.4
//       4.4
Public Module Example
   Sub Main()
      Console.WriteLine(Math.Round(3.44, 1)) 
      Console.WriteLine(Math.Round(3.45, 1)) 
      Console.WriteLine(Math.Round(3.46, 1)) 
      Console.WriteLine()
      
      Console.WriteLine(Math.Round(4.34, 1)) 
      Console.WriteLine(Math.Round(4.35, 1)) 
      Console.WriteLine(Math.Round(4.36, 1)) 
   End Sub  
End Module
' The example displays the following output:
'       3.4
'       3.4
'       3.5
'       
'       4.3
'       4.4
'       4.4
另请参阅

Round(Decimal) Round(Decimal) Round(Decimal) Round(Decimal)

将小数值舍入到最接近的整数值,并将中点值舍入到最接近的偶数。Rounds a decimal value to the nearest integral value, and rounds midpoint values to the nearest even number.

public:
 static System::Decimal Round(System::Decimal d);
public static decimal Round (decimal d);
static member Round : decimal -> decimal
Public Shared Function Round (d As Decimal) As Decimal

参数

d
Decimal Decimal Decimal Decimal

要舍入的小数。A decimal number to be rounded.

返回

最接近 d 参数的整数。The integer nearest the d parameter. 如果 d 的小数部分正好处于两个整数中间,其中一个整数为偶数,另一个整数为奇数,则返回偶数。If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. 请注意,此方法返回 Decimal,而不是整数类型。Note that this method returns a Decimal instead of an integral type.

异常

结果超出了 Decimal 的范围。The result is outside the range of a Decimal.

注解

此方法使用的默认舍入的约定MidpointRounding.ToEvenThis method uses the default rounding convention of MidpointRounding.ToEven. 请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

示例Example

下面的示例演示Round(Decimal)方法。The following example demonstrates the Round(Decimal) method. 请注意, Decimal 4.5 的值将舍入到 4,而不是 5,因为此重载使用默认ToEven约定。Note that the Decimal value of 4.5 rounds to 4 rather than 5, because this overload uses the default ToEven convention.

for (decimal value = 4.2m; value <= 4.8m; value+=.1m )
   Console.WriteLine("{0} --> {1}", value, Math.Round(value));
// The example displays the following output:
//       4.2 --> 4
//       4.3 --> 4
//       4.4 --> 4
//       4.5 --> 4
//       4.6 --> 5
//       4.7 --> 5
//       4.8 --> 5
Module Example
   Public Sub Main()
      For value As Decimal = 4.2d To 4.8d Step .1d
         Console.WriteLine("{0} --> {1}", value, Math.Round(value))
      Next   
   End Sub                                                                 
End Module
' The example displays the following output:
'       4.2 --> 4
'       4.3 --> 4
'       4.4 --> 4
'       4.5 --> 4
'       4.6 --> 5
'       4.7 --> 5
'       4.8 --> 5
另请参阅

Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding)

将小数值舍入到最接近的整数,并为中点值使用指定的舍入规则。Rounds a decimal value to the nearest integer, and uses the specified rounding convention for midpoint values.

public:
 static System::Decimal Round(System::Decimal d, MidpointRounding mode);
public static decimal Round (decimal d, MidpointRounding mode);
static member Round : decimal * MidpointRounding -> decimal
Public Shared Function Round (d As Decimal, mode As MidpointRounding) As Decimal

参数

d
Decimal Decimal Decimal Decimal

要舍入的小数。A decimal number to be rounded.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

在两个数字之间时如何舍入 d 的规范。Specification for how to round d if it is midway between two other numbers.

返回

最接近 d 的整数。The integer nearest d. 如果 d 是两个数字的中值,这两个数字一个为偶数,另一个为奇数,则 mode 确定返回两个数字中的哪一个。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. 请注意,此方法返回 Decimal,而不是整数类型。Note that this method returns a Decimal instead of an integral type.

异常

mode 不是 MidpointRounding 的一个有效值。mode is not a valid value of MidpointRounding.

结果超出了 Decimal 的范围。The result is outside the range of a Decimal.

注解

请参阅中点值和舍入的约定有关舍入中点值的数字信息。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

在舍入中点值时,舍入算法执行相等测试。When rounding midpoint values, the rounding algorithm performs an equality test. 由于浮点格式存在的二进制表示和精度问题,因此方法返回的值可能异常。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 有关详细信息,请参阅“舍入和精度”For more information, see "Rounding and precision".

示例Example

下面的示例显示返回的值Round(Decimal)方法,Round(Decimal, MidpointRounding)方法替换mode自变量ToEven,和Round(Decimal, MidpointRounding)方法替换mode自变量的AwayFromZeroThe following example displays values returned by the Round(Decimal) method, the Round(Decimal, MidpointRounding) method with a mode argument of ToEven, and the Round(Decimal, MidpointRounding) method with a mode argument of AwayFromZero.

Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                  "ToEven", "AwayFromZero");
for (decimal value = 12.0m; value <= 13.0m; value += 0.1m)
   Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}",
                     value, Math.Round(value), 
                     Math.Round(value, MidpointRounding.ToEven),
                     Math.Round(value, MidpointRounding.AwayFromZero));
// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero
//       12         12         12         12
//       12.1       12         12         12
//       12.2       12         12         12
//       12.3       12         12         12
//       12.4       12         12         12
//       12.5       12         12         13
//       12.6       13         13         13
//       12.7       13         13         13
//       12.8       13         13         13
//       12.9       13         13         13
//       13.0       13         13         13
Module Example
   Public Sub Main()
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero")
      For value As Decimal = 12.0d To 13.0d Step .1d
         Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero))
      Next
   End Sub
End Module
' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero
'       12         12         12         12
'       12.1       12         12         12
'       12.2       12         12         12
'       12.3       12         12         12
'       12.4       12         12         12
'       12.5       12         12         13
'       12.6       13         13         13
'       12.7       13         13         13
'       12.8       13         13         13
'       12.9       13         13         13
'       13.0       13         13         13
另请参阅

适用于