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.0 3.4 值的方法和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. 範例會計算陣列的真正平均值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%)從真正的平均值。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. 重複,它會新增至 11.0.1,四捨五入到最接近的整數。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.5Double變數。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.

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

這個未預期的結果是因為遺失的轉換中的有效位數SingleDoubleThis unexpected result is due to a loss of precision in the conversion of the Single value to a Double. 因為產生Double、 16.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.

在許多情況下,如範例所示,遺失有效位數可以最小化或轉型或轉換以消除SingleDecimalIn 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.

傳回

最接近 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.

結果位於 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.

傳回

最接近 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.

備註

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.PositiveInfinity或是Double.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.13 而不是 2.14 所示。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.

例外狀況

備註

請參閱中間點的值和捨入慣例的中點值的數字四捨五入的相關資訊。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.PositiveInfinity或是Double.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 值的方法會傳回 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-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.

傳回

最接近 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.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.PositiveInfinity或是Double.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.13 而不是 2.14 所示。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.PositiveInfinity或是Double.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 值的方法會傳回 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) 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.

傳回

最接近 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.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.

例外狀況

結果位於 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
另請參閱

適用於