Math.Round 方法

定義

將值四捨五入為最接近的整數或是指定的小數位數。Rounds a value to the nearest integer or to the specified number of fractional digits.

多載

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)

將雙精確度浮點數值四捨五入到小數數字的指定數字,並使用中間點值的指定進位慣例。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)

將雙精確度浮點數值四捨五入到最接近的整數,並使用中間點值的指定進位慣例。Rounds a double-precision floating-point value to the nearest integer, and uses the specified rounding convention for midpoint values.

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)

將雙精確度浮點數值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.

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)

將十進位值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。Rounds a decimal value to the nearest integral value, and rounds midpoint values to the nearest even number.

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)
使用指定的進位慣例,將值舍入為指定的小數位數,並將遺失的精確度降至最低。SingleRound a Single value to a specified number of fractional digits by using a specified rounding convention and minimizing the loss of precision. 將轉換Single Decimal為並呼叫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.579 的值舍入至3.58。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 Standard 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. 此範例會計算Decimal值陣列的 true 平均值,然後使用兩個慣例來計算陣列中的值時的平均值。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. 在此範例中,真正的平均值和表示進位到最接近的結果是相同的。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方法會將原始值乘以 10n,其中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.

  • 當要舍入的值是, SingleDouble不是或Decimal時。When 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四捨五入值的多載,您可以Double將變更為Decimal 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.

  • 定義自訂的進位演算法,它會執行「近乎相等」的測試,以判斷要四捨五入的值是否可接受接近中間點值。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

方法包含接受類型Decimal為和Double之引數的多載。 RoundThe Round method includes overloads that accept arguments of type Decimal and Double. 沒有方法可以舍入類型Single的值。There are no methods that round values of type Single. 如果您Single將值傳遞至Round方法的其中一個多載,則會將它轉換( C#在中)或Double轉換(在 Visual Basic 中)至,並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. 當16.325 的Round值傳遞至方法,並使用舍入至最接近的慣例舍入兩個小數位數時,結果會是16.33,而不是預期的16.32 結果。 SingleWhen 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值轉換Double成時,遺失有效位數。This unexpected result is due to a loss of precision in the conversion of the Single value to a Double. 由於16.325000762939453 的Double結果值不是中間值且大於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值轉型或轉換Decimal為,以最小化或消除精確度的損失。In 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. 請注意,因為這是縮小轉換,所以它需要使用 cast 運算子或呼叫轉換方法。Note that, because this is a narrowing conversion, it requires using a cast operator or calling a conversion method.

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

要四捨五入的十進位數字。A decimal number to be rounded.

decimals
Int32

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

mode
MidpointRounding

指定如果 d 介於另外兩個數字中間的四捨五入法。Specification for how to round d if it is midway between two other numbers.

傳回

最接近 d 的數字,其中包含等於 decimals 的小數位數。The number nearest to d that contains a number of fractional digits equal to decimals. 如果 d 的小數位數少於 decimalsd 傳回時不會變更。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.
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
End Class
'
'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)

將雙精確度浮點數值四捨五入到小數數字的指定數字,並使用中間點值的指定進位慣例。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

要四捨五入的雙精確度浮點數。A double-precision floating-point number to be rounded.

digits
Int32

傳回值中小數點後數字的數目。The number of fractional digits in the return value.

mode
MidpointRounding

指定如果 value 介於另外兩個數字中間的四捨五入法。Specification for how to round value if it is midway between two other numbers.

傳回

最接近 value 的數字,其中包含等於 digits 的小數位數。The number nearest to value that has a number of fractional digits equal to digits. 如果 value 的小數位數少於 digitsvalue 傳回時不會變更。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.NaN會傳回。If the value of the value argument is Double.NaN, the method returns Double.NaN. 如果valueDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別Double.NegativeInfinity傳回或。Double.PositiveInfinityIf 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.13,而不是2.14。This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. 發生這種情況的原因是value在內部,方法乘以 10位數,而在此情況下的乘法運算會受到失去精確度的影響。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)

將雙精確度浮點數值四捨五入到最接近的整數,並使用中間點值的指定進位慣例。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

要四捨五入的雙精確度浮點數。A double-precision floating-point number to be rounded.

mode
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.NaN會傳回。If the value of the value argument is Double.NaN, the method returns Double.NaN. 如果valueDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別Double.NegativeInfinity傳回或。Double.PositiveInfinityIf value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

範例Example

下列範例會顯示Round(Double)方法所傳回的值Round(Double, MidpointRounding) 、具有mode ToEven mode引數的方法,以及Round(Double, MidpointRounding)具有之AwayFromZero引數的方法。The 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 值的方法時,會傳回11,而不是12。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#4] [!code-vbSystem.Math.Round#4][!code-csharpSystem.Math.Round#4] [!code-vbSystem.Math.Round#4]

另請參閱

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

要四捨五入的雙精確度浮點數。A double-precision floating-point number to be rounded.

digits
Int32

傳回值中小數點後數字的數目。The number of fractional digits in the return value.

傳回

最接近 value 的數字,其中包含等於 digits 的小數位數。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.ToEven慣例。This 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.NaN會傳回。If the value of the value argument is Double.NaN, the method returns Double.NaN. 如果valueDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別Double.NegativeInfinity傳回或。Double.PositiveInfinityIf 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.13,而不是2.14。This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. 發生這種情況的原因是value在內部,方法乘以 10位數,而在此情況下的乘法運算會受到失去精確度的影響。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#2] [!code-vbSystem.Math.Round#2][!code-csharpSystem.Math.Round#2] [!code-vbSystem.Math.Round#2]

另請參閱

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

要四捨五入的雙精確度浮點數。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.ToEven慣例。This 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.NaN會傳回。If the value of the a argument is Double.NaN, the method returns Double.NaN. 如果aDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別Double.NegativeInfinity傳回或。Double.PositiveInfinityIf a is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

從 Visual Basic 15.8 開始,如果您將Round方法所傳回的值傳遞給任何整數轉換函數,或傳回的Round double 值,則會優化雙精確度轉換的效能。會自動轉換成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
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 值的方法時,會傳回11,而不是12。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)

將十進位值四捨五入到小數數字的指定數字,並將中間點值四捨五入到最接近的偶數。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

要四捨五入的十進位數字。A decimal number to be rounded.

decimals
Int32

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

傳回

最接近 d 的數字,其中包含等於 decimals 的小數位數。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.ToEven慣例。This 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)

將十進位值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。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

要四捨五入的十進位數字。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.ToEven慣例。This 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)

將十進位值四捨五入到最接近的整數,並使用中間點值的指定進位慣例。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

要四捨五入的十進位數字。A decimal number to be rounded.

mode
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 mode引數的方法,以及Round(Decimal, MidpointRounding)具有之AwayFromZero引數的方法。The 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

另請參閱

適用於