Math.Round 方法

定義

將值四捨五入為最接近的整數或是指定的小數位數。

多載

Round(Double, Int32, MidpointRounding)

使用指定的四捨五入慣例,將雙精確度浮點數四捨五入到指定的小數位數。

Round(Decimal, Int32, MidpointRounding)

使用指定的四捨五入慣例,將十進位值四捨五入為指定的小數位數。

Round(Double, MidpointRounding)

使用指定的四捨五入慣例,將雙精確度浮點數四捨五入為整數。

Round(Double, Int32)

將雙精確度浮點數值四捨五入到小數數字的指定數字,並將中間點值四捨五入到最接近的偶數。

Round(Decimal, Int32)

將十進位值四捨五入到小數數字的指定數字,並將中間點值四捨五入到最接近的偶數。

Round(Double)

將雙精確度浮點數值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。

Round(Decimal)

將十進位值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。

Round(Decimal, MidpointRounding)

使用指定的四捨五入慣例,將十進位值四捨五入。

範例

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 (Double) Math.Round (Decimal, Int32) Math.Round (Decimal、MidpointRounding) Math.Round (Double、Int32) Math.Round (Double、MidpointRounding) Math.Round (Decimal、Int32、MidpointRounding) Math.Round (Double、Int32、MidpointRounding)

備註

本節內容:

我呼叫哪一種方法?

您可以使用下表來選取適當的進位方法。 除了 Math.Round 方法之外,它也包含 Math.CeilingMath.Floor

收件者 呼叫
使用四捨五入到最接近慣例,將數位四捨五入為整數。 Round(Decimal)
-或-
Round(Double)
使用指定的四捨五入慣例,將數位四捨五入為整數。 Round(Decimal, MidpointRounding)
-或-
Round(Double, MidpointRounding)
使用四捨五入為最接近慣例,將數位四捨五入為指定的小數位數。 Round(Decimal, Int32)
-或-
Round(Double, Int32)
使用指定的四捨五入慣例,將數位四捨五入為指定的小數位數。 Round(Decimal, Int32, MidpointRounding)
-或-
Round(Double, Int32, MidpointRounding)
Single使用指定的四捨五入慣例,將值四捨五入為指定的小數位數,並將精確度損失降到最低。 SingleDecimal轉換為 ,並呼叫 Round(Decimal, Int32, MidpointRounding)
將數位四捨五入為指定的小數位數,同時將四捨五入中間點值中精確度的問題降到最低。 呼叫實作「大於或近似等於」比較的捨入方法。 請參閱 捨入和有效位數
將小數值四捨五入為大於小數值的整數。 例如,四捨五入 3.1 到 4。 Ceiling
將小數值四捨五入為小於小數值的整數。 例如,四捨五入 3.9 到 3。 Floor

中間點值和四捨五入慣例

四捨五入牽涉到將具有指定有效位數的數值轉換為精確度較低的值。 例如,您可以使用 Round(Double) 方法將 3.4 到 3.0 的值四捨五入,而 方法可將 Round(Double, Int32) 3.579 的值四捨五入為 3.58。

在中間點值中,結果中最小有效位數後面的值會精確介於兩個數字之間的一半。 例如,如果要四捨五入為兩個小數字數,則 3.47500 是中間點值,而 7.500 是中間點值,如果要四捨五入為整數。 在這些情況下,如果使用四捨五入到最接近的策略,則不需要四捨五入慣例,就無法輕鬆地識別最接近的值。

方法 Round 支援兩個四捨五入慣例來處理中間點值:

  • 四捨五入為零

    中間點值會四捨五入到下一個數位,而距離零。 例如,3.75 四捨五入為 3.8、3.85 四捨五入為 3.9、-3.75 四捨五入為 -3.8,而 -3.85 四捨五入為 -3.9。 這個形式的四捨五入是由列舉成員表示 MidpointRounding.AwayFromZero

  • 四捨五入為最接近偶數,或銀行員捨入

    中間點值會四捨五入為最接近的偶數。 例如,3.75 和 3.85 會四捨五入為 3.8,而 -3.75 和 -3.85 會四捨五入為 -3.8。 這個形式的四捨五入是由列舉成員表示 MidpointRounding.ToEven

注意

在 .NET Core 3.0 和更新版本中,可透過 列舉取得 MidpointRounding 三個額外的進位策略。 所有情況下都會使用這些策略,而不只是用於和的中間點值MidpointRounding.ToEvenMidpointRounding.AwayFromZero

四捨五入是最廣為人知的四捨五入形式,而捨入到最接近,甚至是財務和統計作業的標準。 它符合 IEEE Standard 754 第 4 節。 在多個捨入作業中使用時,捨入至最接近甚至會減少單一方向一致捨入中間點值所造成的四捨五入錯誤。 在某些情況下,此捨入錯誤可能相當重要。

下列範例說明以單一方向一致四捨五入中間點值所造成的偏差。 此範例會計算值陣列 Decimal 的真平均數,然後使用兩個慣例來計算陣列中的值四捨五入時的平均數。 在此範例中,當四捨五入到最接近時所產生的 true 平均值和平均值相同。 不過,從零四捨五入時所產生的平均數與 .05 (或 3.6%) 與 true 平均數不同。

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
open System

let values = [| 1.15m; 1.25m; 1.35m; 1.45m; 1.55m; 1.65m |]
let mutable sum = 0m

// Calculate true mean.
for value in values do
    sum <- sum + value

printfn $"True mean:     {sum / decimal values.Length:N2}"

// Calculate mean with rounding away from zero.
sum <- 0m
for value in values do
    sum <- sum + Math.Round(value, 1, MidpointRounding.AwayFromZero)

printfn $"AwayFromZero:  {sum / decimal values.Length:N2}"

// Calculate mean with rounding to nearest.
sum <- 0m
for value in values do
    sum <- sum + Math.Round(value, 1, MidpointRounding.ToEven)

printfn $"ToEven:        {sum / decimal values.Length:N2}"

// The example displays the following output:
//       True mean:     1.40
//       AwayFromZero:  1.45
//       ToEven:        1.40
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)

' The example displays the following output:
'       True mean:     1.40
'       AwayFromZero:  1.45
'       ToEven:        1.40

根據預設, Round 方法會使用四捨五入到最接近的偶數慣例。 下表列出 方法的多 Round 載,以及每個使用的四捨五入慣例。

多載 四捨五入慣例
Round(Decimal) ToEven
Round(Double) ToEven
Round(Decimal, Int32) ToEven
Round(Double, Int32) ToEven
Round(Decimal, MidpointRounding) mode 參數決定。
Round(Double, MidpointRounding) mode 參數決定
Round(Decimal, Int32, MidpointRounding) mode 參數決定
Round(Double, Int32, MidpointRounding) mode 參數決定

四捨五入和有效位數

為了判斷四捨五入作業是否牽涉到中間點值, Round 方法會將原始值乘以 10n,其中 n 是傳回值中所需的小數位數,然後判斷值的剩餘小數部分是否大於或等於 .5。 這是相等測試的微幅變化,如參考主題的一節 Double 所討論,因為浮點格式的二進位表示和精確度問題,所以對浮點值的相等測試有問題。 這表示由於遺失有效位數) 而略小於 .5 (的任何小數部分都不會向上四捨五入。

下面範例會說明此問題。 它會重複將 .1 新增至 11.0,並將結果四捨五入到最接近的整數。 11.5 應該使用中間點捨入慣例 (ToEven 或) 四捨五入為 AwayFromZero 12。 不過,如範例的輸出所示,它不會。 此範例會使用 「R」 標準數值格式字串 來顯示浮點值的完整有效位數,並顯示要捨入的值在重複加法期間遺失有效位數,而其值實際上是 11.4999999999999998。 因為 .499999999999998 小於 .5,所以中間點捨入慣例不會生效,而且值會捨入。 如範例所示,如果您將常數值 11.5 指派給 Double 變數,就不會發生此問題。

public static void Example()
{
    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
open System

let roundValueAndAdd (value: double) =
    printfn $"{value,5:N1} {value,20:R}  {Math.Round(value, MidpointRounding.ToEven),12} {Math.Round(value, MidpointRounding.AwayFromZero),15}"
    value + 0.1

printfn "%5s %20s  %12s %15s\n" "Value" "Full Precision" "ToEven" "AwayFromZero"
let mutable value = 11.1
for _ = 0 to 5 do
    value <- roundValueAndAdd value

printfn ""

value <- 11.5
roundValueAndAdd value
|> ignore

// 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
Public Sub Example()
    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 + 0.1
End Function

' 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

四捨五入中間點值中精確度的問題最有可能在下列情況下發生:

  • 當小數值無法以浮點類型的二進位格式精確表示時。

  • 從一或多個浮點運算計算要四捨五入的值時。

  • 當要捨入的值是 , Single 而不是 DoubleDecimal時。 如需詳細資訊,請參閱下一節 :四捨五入和單精度浮點值

如果四捨五入作業缺少精確度有問題,您可以執行下列動作:

  • 如果捨入作業呼叫會四捨 Double 五入值的多載,您可以將 變更 DoubleDecimal 值,並改為呼叫會四捨 Decimal 五入值的多載。 Decimal雖然數據類型也有表示和遺失精確度的問題,但這些問題較不常見。

  • 定義自定義捨入演算法,以執行「幾乎相等」測試,以判斷要四捨五入的值是否可接受接近中間點值。 下列範例會 RoundApproximate 定義方法,檢查小數值是否足以接近中間點值,以受限於中間點捨入。 如範例的輸出所示,它會修正上一個範例所示的進位問題。

    public static void Example()
    {
        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
    
    open System
    
    let roundApproximate dbl digits margin mode =
        let fraction = dbl * Math.Pow(10, digits)
        let value = Math.Truncate fraction
        let fraction = fraction - value
        if fraction = 0 then
            dbl
        else
            let tolerance = margin * dbl
            // Determine whether this is a midpoint value.
            if (fraction >= 0.5 - tolerance) && (fraction <= 0.5 + tolerance) then
                if mode = MidpointRounding.AwayFromZero then
                    (value + 1.) / Math.Pow(10, digits)
                elif value % 2. <> 0 then
                    (value + 1.) / Math.Pow(10, digits)
                else
                    value / Math.Pow(10, digits)
            // Any remaining fractional value greater than .5 is not a midpoint value.
            elif fraction > 0.5 then
                (value + 1.) / Math.Pow(10, digits)
            else
                value / Math.Pow(10, digits)
    
    
    let roundValueAndAdd value =
        let tolerance = 8e-14
        let round = roundApproximate value 0 tolerance
    
        printfn $"{value,5:N1} {value,20:R}  {round MidpointRounding.ToEven,12} {round MidpointRounding.AwayFromZero,15}"
        value + 0.1
    
    printfn "%5s %20s  %12s %15s\n" "Value" "Full Precision" "ToEven" "AwayFromZero"
    let mutable value = 11.1
    for _ = 0 to 5 do
        value <- roundValueAndAdd value
    
    printfn ""
    
    value <- 11.5
    roundValueAndAdd value 
    |> ignore
    
    // 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
    
    Public Sub Example()
        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 = 0.00000000000008
        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 + 0.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 >= 0.5 - tolerance) And (fraction <= 0.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 > 0.5 Then
            Return (value + 1) / Math.Pow(10, digits)
        Else
            Return value / Math.Pow(10, digits)
        End If
    End Function
    
    ' 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
    

四捨五入和單精度浮點值

方法 Round 包含接受 型 Decimal 別和 Double自變數的多載。 沒有方法會四捨五入類型 Single的值。 如果您將值傳遞至方法的Round其中一個Single多載,它會在 C#) 中轉換 (,或在 Visual Basic Double) 中轉換成 (,並呼叫具有 參數的對應RoundDouble載。 雖然這是擴展轉換,但通常涉及遺失精確度,如下列範例所示。 Single當值為 16.325 傳遞至 方法,Round並使用四捨五入為最接近慣例四捨五入至兩個小數位數時,結果為 16.33,而不是 16.32 的預期結果。

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
// In F#, 'float', 'float64', and 'double' are aliases for System.Double...
// 'float32' and 'single' are aliases for System.Single
open System

let value = 16.325f
printfn $"Widening Conversion of {value:R} (type {value.GetType().Name}) to {double value:R} (type {(double value).GetType().Name}): "
printfn $"{Math.Round(decimal value, 2)}"
printfn $"{Math.Round(decimal value, 2, MidpointRounding.AwayFromZero)}"
printfn ""

let decValue = decimal value
printfn $"Cast of {value:R} (type {value.GetType().Name}) to {decValue} (type {decValue.GetType().Name}): "
printfn $"{Math.Round(decValue, 2)}"
printfn $"{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
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()

' 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

此非預期的結果是因為將值Double轉換成 Single 時遺失有效位數。 因為產生的 Double 值為 16.325000762939453 不是中間點值,而且大於 16.325,所以一律會向上捨入。

在許多情況下,如範例所說明,藉由轉型或將值Decimal轉換成 Single ,即可將精確度遺失降至最低或消除。 請注意,因為這是縮小轉換,所以需要使用轉換運算符或呼叫轉換方法。

Round(Double, Int32, MidpointRounding)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

使用指定的四捨五入慣例,將雙精確度浮點數四捨五入到指定的小數位數。

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

要四捨五入的雙精確度浮點數。

digits
Int32

傳回值中小數點後數字的數目。

mode
MidpointRounding

其中一個列舉值,指定要使用的四捨五入策略。

傳回

具有 digits 四捨五入為小數位數的數位 value 。 如果 value 的小數位數少於 digitsvalue 傳回時不會變更。

例外狀況

digits 小於 0 或大於 15。

mode 不是有效的 MidpointRounding 值。

備註

自變數的值 digits 可以介於 0 到 15 之間。 類型所 Double 支援的整數和小數位數上限為15。

如需使用中間點值四捨五入數位的相關信息,請參閱 中間點值和四捨 五入慣例。

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

如果自變數的值 valueDouble.NaN,則方法會傳 Double.NaN回 。 如果 為 valueDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別傳 Double.PositiveInfinity 回 或 Double.NegativeInfinity

範例

下列範例示範如何搭配 MidpointRounding 列舉使用 Round(Double, Int32, MidpointRounding) 方法。


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

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

// Round a negative value using a MidpointRounding value.
result = Math.Round(-3.45, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.ToEven)");
result = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(-3.47, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result,4} = Math.Round({-3.47,5}, 1, MidpointRounding.ToZero)\n");

// 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.47, 1, MidpointRounding.ToZero)

//         -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
//         -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
//         -3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
// Round a positive and a negative value using the default.
let result = Math.Round(3.45, 1)
printfn $"{result,4} = Math.Round({3.45,5}, 1)"
let result = Math.Round(-3.45, 1)
printfn $"{result,4} = Math.Round({-3.45,5}, 1)\n"

// Round a positive value using a MidpointRounding value.
let result = Math.Round(3.45, 1, MidpointRounding.ToEven)
printfn $"{result,4} = Math.Round({3.45,5}, 1, MidpointRounding.ToEven)"
let result = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
printfn $"{result,4} = Math.Round({3.45,5}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(3.47, 1, MidpointRounding.ToZero)
printfn $"{result,4} = Math.Round({3.47,5}, 1, MidpointRounding.ToZero)\n"

// Round a negative value using a MidpointRounding value.
let result = Math.Round(-3.45, 1, MidpointRounding.ToEven)
printfn $"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.ToEven)"
let result = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
printfn $"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(-3.47, 1, MidpointRounding.ToZero)
printfn $"{result,4} = Math.Round({-3.47,5}, 1, MidpointRounding.ToZero)\n"

// 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.47, 1, MidpointRounding.ToZero)

//         -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
//         -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
//         -3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
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()

'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) ,方法可能不會像 參數所 mode 指定的四捨五入中間點值。 下列範例將說明這點,其中 2.135 會四捨五入為 2.13,而不是 2.14。 這是因為方法在內部乘 value 以 10位數,而在此情況下乘法運算會因為遺失精確度而受到影響。

double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
foreach (double value in values)
   Console.WriteLine("{0} --> {1}", value,
                     Math.Round(value, 2, MidpointRounding.AwayFromZero));

// The example displays the following output:
//       2.125 --> 2.13
//       2.135 --> 2.13
//       2.145 --> 2.15
//       3.125 --> 3.13
//       3.135 --> 3.14
//       3.145 --> 3.15
open System

let values = [| 2.125; 2.135; 2.145; 3.125; 3.135; 3.145 |]
for value in values do
    printfn $"{value} --> {Math.Round(value, 2, MidpointRounding.AwayFromZero)}"
// The example displays the following output:
//       2.125 --> 2.13
//       2.135 --> 2.13
//       2.145 --> 2.15
//       3.125 --> 3.13
//       3.135 --> 3.14
//       3.145 --> 3.15
Module Example
   Public Sub Main()
      Dim values() As Double = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }
      For Each value As Double In values
         Console.WriteLine("{0} --> {1}", value, 
                           Math.Round(value, 2, MidpointRounding.AwayFromZero))
      Next
   End Sub
End Module
' The example displays the following output:
'       2.125 --> 2.13
'       2.135 --> 2.13
'       2.145 --> 2.15
'       3.125 --> 3.13
'       3.135 --> 3.14
'       3.145 --> 3.15

另請參閱

適用於

Round(Decimal, Int32, MidpointRounding)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

使用指定的四捨五入慣例,將十進位值四捨五入為指定的小數位數。

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

要四捨五入的十進位數字。

decimals
Int32

傳回值中的小數位數。

mode
MidpointRounding

其中一個列舉值,指定要使用的四捨五入策略。

傳回

具有 decimals 四捨五入之小數位數 d 的數位。 如果 d 的小數位數少於 decimalsd 傳回時不會變更。

例外狀況

decimals 小於 0 或大於 28。

mode 不是有效的 MidpointRounding 值。

結果位於 Decimal 的範圍之外。

備註

如需使用中間點值四捨五入數位的相關信息,請參閱 中間點值和四捨 五入慣例。

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

自變數的值 decimals 可以介於 0 到 28 之間。

範例

下列範例示範如何搭配 MidpointRounding 列舉使用 Round 方法。

decimal result;

// Round a positive value using different strategies.
// The precision of the result is 1 decimal place.

result = Math.Round(3.45m, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result} = Math.Round({3.45m}, 1, MidpointRounding.ToEven)");
result = Math.Round(3.45m, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result} = Math.Round({3.45m}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(3.47m, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result} = Math.Round({3.47m}, 1, MidpointRounding.ToZero)\n");

// Round a negative value using different strategies.
// The precision of the result is 1 decimal place.

result = Math.Round(-3.45m, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result} = Math.Round({-3.45m}, 1, MidpointRounding.ToEven)");
result = Math.Round(-3.45m, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result} = Math.Round({-3.45m}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(-3.47m, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result} = Math.Round({-3.47m}, 1, MidpointRounding.ToZero)\n");

/*
This code example produces the following results:

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

-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
-3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
*/
// Round a positive value using different strategies.
// The precision of the result is 1 decimal place.

let result = Math.Round(3.45m, 1, MidpointRounding.ToEven)
printfn $"{result} = Math.Round({3.45m}, 1, MidpointRounding.ToEven)"
let result = Math.Round(3.45m, 1, MidpointRounding.AwayFromZero)
printfn $"{result} = Math.Round({3.45m}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(3.47m, 1, MidpointRounding.ToZero)
printfn $"{result} = Math.Round({3.47m}, 1, MidpointRounding.ToZero)\n"

// Round a negative value using different strategies.
// The precision of the result is 1 decimal place.

let result = Math.Round(-3.45m, 1, MidpointRounding.ToEven)
printfn $"{result} = Math.Round({-3.45m}, 1, MidpointRounding.ToEven)"
let result = Math.Round(-3.45m, 1, MidpointRounding.AwayFromZero)
printfn $"{result} = Math.Round({-3.45m}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(-3.47m, 1, MidpointRounding.ToZero)
printfn $"{result} = Math.Round({-3.47m}, 1, MidpointRounding.ToZero)\n"

// This code example produces the following results:

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

// -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
// -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
// -3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
Dim result As Decimal = 0D
Dim posValue As Decimal = 3.45D
Dim negValue As Decimal = -3.45D

' Round a positive value using different strategies.
' 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)
result = Math.Round(posValue, 1, MidpointRounding.ToZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToZero)",
                   result, posValue)
Console.WriteLine()

' Round a negative value using different strategies.
' 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)
result = Math.Round(negValue, 1, MidpointRounding.ToZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToZero)",
                   result, negValue)
Console.WriteLine()

'This code example produces the following results:
'
'        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.ToZero)
'
'        -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.ToZero)
'

另請參閱

適用於

Round(Double, MidpointRounding)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

使用指定的四捨五入慣例,將雙精確度浮點數四捨五入為整數。

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

要四捨五入的雙精確度浮點數。

mode
MidpointRounding

其中一個列舉值,指定要使用的四捨五入策略。

傳回

四捨五入為的整數 value 。 這個方法會傳 Double 回 ,而不是整數型別。

例外狀況

mode 不是有效的 MidpointRounding 值。

備註

如需使用中間點值四捨五入數位的相關信息,請參閱 中間點值和四捨 五入慣例。

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

如果自變數的值 valueDouble.NaN,則方法會傳 Double.NaN回 。 如果 為 valueDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別傳 Double.PositiveInfinity 回 或 Double.NegativeInfinity

範例

下列範例會顯示由 方法傳 Round(Double, MidpointRounding) 回的值,其值有不同的 mode 值。

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($"{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}");

foreach (var value in values)
    Console.WriteLine($"{value,-10:R} {Math.Round(value),-10} " +
        $"{Math.Round(value, MidpointRounding.ToEven),-10} " +
        $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " +
        $"{Math.Round(value, MidpointRounding.ToZero),-15}");

// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12         12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13         13         13         13              13
open System

let values = 
    [| 12.; 12.1; 12.2; 12.3; 12.4; 12.5
       12.6; 12.7; 12.8; 12.9; 13. |]

printfn "%-10s %-10s %-10s %-15s %-15s" "Value" "Default" "ToEven" "AwayFromZero" "ToZero"

for value in values do
    $"{value,-10:R} {Math.Round(value),-10} " +
    $"{Math.Round(value, MidpointRounding.ToEven),-10} " +
    $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " +
    $"{Math.Round(value, MidpointRounding.ToZero),-15}"
    |> printfn "%s"
    
// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12         12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13         13         13         13              13
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} {4,-15}", "Value", "Default",
                "ToEven", "AwayFromZero", "ToZero")
For Each value In values
    Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}",
                   value, Math.Round(value),
                   Math.Round(value, MidpointRounding.ToEven),
                   Math.Round(value, MidpointRounding.AwayFromZero),
                   Math.Round(value, MidpointRounding.ToZero))
Next

' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero     ToZero
'       12         12         12         12               12
'       12.1       12         12         12               12
'       12.2       12         12         12               12
'       12.3       12         12         12               12
'       12.4       12         12         12               12
'       12.5       12         12         13               12
'       12.6       13         13         13               12
'       12.7       13         13         13               12
'       12.8       13         13         13               12
'       12.9       13         13         13               12
'       13         13         13         13               13

給呼叫者的注意事項

由於遺失可能因為將十進位值表示為浮點數或對浮點數執行算術運算而造成的精確度遺失,在某些情況下, Round(Double, MidpointRounding) 方法可能不會將中間點值四捨五入到最接近的偶數整數。 在下列範例中,因為浮點值 .1 沒有有限的二進位表示法,所以第一次呼叫 Round(Double) 值為 11.5 的 方法會傳回 11,而不是 12。

using System;

public class Example
{
   public static void Main()
   {
      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} --> {1}", value, Math.Round(value,
                        MidpointRounding.AwayFromZero));
      return value + .1;
   }
}
// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
open System

let roundValueAndAdd (value: float) =
      printfn $"{value} --> {Math.Round(value, MidpointRounding.AwayFromZero)}"
      value + 0.1

let mutable value = 11.1
for _ = 0 to 5 do
    value <- roundValueAndAdd value

printfn ""

value <- 11.5
roundValueAndAdd value
|> ignore

// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
Module Example
   Public Sub Main()
      Dim value As Double = 11.1
      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} --> {1}", value, Math.Round(value, 
                        MidpointRounding.AwayFromZero))
      Return value + .1
   End Function   
End Module
' The example displays the following output:
'       11.1 --> 11
'       11.2 --> 11
'       11.3 --> 11
'       11.4 --> 11
'       11.5 --> 11
'       11.6 --> 12
'       
'       11.5 --> 12

另請參閱

適用於

Round(Double, Int32)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

將雙精確度浮點數值四捨五入到小數數字的指定數字,並將中間點值四捨五入到最接近的偶數。

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

要四捨五入的雙精確度浮點數。

digits
Int32

傳回值中小數點後數字的數目。

傳回

最接近 value 的數字,其中包含等於 digits 的小數位數。

例外狀況

digits 小於 0 或大於 15。

備註

自變數的值 digits 可以介於 0 到 15 之間。 類型所 Double 支援的整數和小數位數上限為15。

這個方法使用的預設四捨五入慣例 MidpointRounding.ToEven。 如需使用中間點值四捨五入數位的相關信息,請參閱 中間點值和四捨 五入慣例。

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

如果自變數的值 valueDouble.NaN,則方法會傳 Double.NaN回 。 如果 為 valueDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別傳 Double.PositiveInfinity 回 或 Double.NegativeInfinity

範例

下列範例會將具有兩個小數位數的雙精度浮點數四捨五入為具有單一小數位數的雙精度浮點數。

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
open System

printfn $"{Math.Round(3.44, 1)}" //Returns 3.4.
printfn $"{Math.Round(3.45, 1)}" //Returns 3.4.
printfn $"{Math.Round(3.46, 1)}" //Returns 3.5.

printfn $"{Math.Round(4.34, 1)}" // Returns 4.3
printfn $"{Math.Round(4.35, 1)}" // Returns 4.4
printfn $"{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 最接近的偶數值。 下列範例將說明這點,其中 2.135 會四捨五入為 2.13,而不是 2.14。 這是因為方法在內部乘 value 以 10位數,而在此情況下乘法運算會因為遺失精確度而受到影響。

using System;

public class Example
{
   public static void Main()
   {
      double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
      foreach (double value in values)
         Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));
   }
}
// The example displays the following output:
//       2.125 --> 2.12
//       2.135 --> 2.13
//       2.145 --> 2.14
//       3.125 --> 3.12
//       3.135 --> 3.14
//       3.145 --> 3.14
open System

let values = [| 2.125; 2.135; 2.145; 3.125; 3.135; 3.145 |]
for value in values do
    printfn $"{value} --> {Math.Round(value, 2)}"
// The example displays the following output:
//       2.125 --> 2.12
//       2.135 --> 2.13
//       2.145 --> 2.14
//       3.125 --> 3.12
//       3.135 --> 3.14
//       3.145 --> 3.14
Module Example
   Public Sub Main()
      Dim values() As Double = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }
      For Each value As Double In values
         Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2))
      Next
   End Sub
End Module
' The example displays the following output:
'       2.125 --> 2.12
'       2.135 --> 2.13
'       2.145 --> 2.14
'       3.125 --> 3.12
'       3.135 --> 3.14
'       3.145 --> 3.14

另請參閱

適用於

Round(Decimal, Int32)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

將十進位值四捨五入到小數數字的指定數字,並將中間點值四捨五入到最接近的偶數。

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

要四捨五入的十進位數字。

decimals
Int32

傳回值中的小數位數。

傳回

最接近 d 的數字,其中包含等於 decimals 的小數位數。

例外狀況

decimals 小於 0 或大於 28。

結果位於 Decimal 的範圍之外。

備註

自變數的值 decimals 可以介於 0 到 28 之間。

這個方法使用的預設四捨五入慣例 MidpointRounding.ToEven。 如需使用中間點值四捨五入數位的詳細資訊,請參閱 中間點值和四捨五入慣例

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

範例

下列範例會將具有兩個小數位數的十進位值四捨五入為具有單一小數位數的值。

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
open System

printfn 
    $"""{Math.Round(3.44m, 1)}
{Math.Round(3.45m, 1)}
{Math.Round(3.46m, 1)}

{Math.Round(4.34m, 1)}
{Math.Round(4.35m, 1)}
{Math.Round(4.36m, 1)}"""

// The example displays the following output:
//       3.4
//       3.4
//       3.5
//
//       4.3
//       4.4
//       4.4
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))

' The example displays the following output:
'       3.4
'       3.4
'       3.5
'       
'       4.3
'       4.4
'       4.4

另請參閱

適用於

Round(Double)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

將雙精確度浮點數值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。

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 的整數。 如果 a 的小數部分正好為兩個整數的中間數 (一個為偶數,另一個為奇數),則會傳回偶數。 請注意,這個方法會傳回 Double,而不是整數類型。

備註

這個方法使用的預設四捨五入慣例 MidpointRounding.ToEven。 如需使用中間點值四捨五入數位的詳細資訊,請參閱 中間點值和四捨五入慣例

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

如果自變數的值 aDouble.NaN,則方法會傳 Double.NaN回 。 如果 為 aDouble.PositiveInfinityDouble.NegativeInfinity,則方法會分別傳 Double.PositiveInfinity 回 或 Double.NegativeInfinity

從 Visual Basic 15.8 開始,如果您將 Round 方法所傳回的值傳遞給任何整數轉換函式,或 Round 所傳回的 Double 值自動轉換為整數且 Option Stric 設為 Off,從雙精確度浮點數到整數的轉換會達到最佳效能。 這項最佳化可讓程式碼執行速度更快,對於執行大量轉換 (目標為整數類型) 的程式碼,速度最快提高為兩倍。 下列範例說明這類優化的轉換:

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

範例

下列範例示範四捨五入為最接近的整數值。

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
open System

printfn "Classic Math.Round in F#"
printfn $"{Math.Round(4.4)}" // 4
printfn $"{Math.Round(4.5)}" // 4
printfn $"{Math.Round(4.6)}" // 5
printfn $"{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) 方法可能不會將中間點值四捨五入到最接近的偶數整數。 在下列範例中,因為浮點值 .1 沒有有限的二進位表示法,所以第一次呼叫 Round(Double) 值為 11.5 的 方法會傳回 11,而不是 12。

using System;

public class Example
{
   public static void Main()
   {
      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} --> {1}", value, Math.Round(value));
      return value + .1;
   }
}
// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
open System

let roundValueAndAdd (value: float) =
    printfn $"{value} --> {Math.Round value}"
    value + 0.1

let mutable value = 11.1

for _ = 0 to 5 do
    value <- roundValueAndAdd value

printfn ""

value <- 11.5
roundValueAndAdd value
|> ignore

// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
Module Example
   Public Sub Main()
      Dim value As Double = 11.1
      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} --> {1}", value, Math.Round(value))
      Return value + .1
   End Function   
End Module
' The example displays the following output:
'       11.1 --> 11
'       11.2 --> 11
'       11.3 --> 11
'       11.4 --> 11
'       11.5 --> 11
'       11.6 --> 12
'       
'       11.5 --> 12

另請參閱

適用於

Round(Decimal)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

將十進位值四捨五入到最接近的整數值,並將中間點值四捨五入到最接近的偶數。

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

要四捨五入的十進位數字。

傳回

最接近 d 參數的整數。 如果 d 的小數部分正好為兩個整數的中間數 (一個為偶數,另一個為奇數),則會傳回偶數。 請注意,這個方法會傳回 Decimal,而不是整數類型。

例外狀況

結果位於 Decimal 的範圍之外。

範例

下列範例示範 Round(Decimal) 方法。 Decimal 4.5 的值會四捨五入為 4,而不是 5,因為此多載會使用預設ToEven慣例。

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
open System

for value in 4.2m .. 0.1m .. 4.8m do
    printfn $"{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

備註

這個方法使用的預設四捨五入慣例 MidpointRounding.ToEven。 如需使用中間點值四捨五入數位的詳細資訊,請參閱 中間點值和四捨五入慣例

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

另請參閱

適用於

Round(Decimal, MidpointRounding)

Source:
Math.cs
Source:
Math.cs
Source:
Math.cs

使用指定的四捨五入慣例,將十進位值四捨五入。

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

要四捨五入的十進位數字。

mode
MidpointRounding

其中一個列舉值,指定要使用的四捨五入策略。

傳回

四捨五入為的整數 d 。 這個方法會傳 Decimal 回 ,而不是整數型別。

例外狀況

mode 不是有效的 MidpointRounding 值。

結果位於 Decimal 的範圍之外。

備註

如需使用中間點值四捨五入數位的詳細資訊,請參閱 中間點值和四捨五入慣例

重要

將中間點值捨入時,捨入演算法會執行相等性測試。 因為二進位表示法與浮點數格式的精確度問題,方法可能傳回非預期的值。 如需詳細資訊,請參閱 四捨五入和有效位數

範例

下列範例會顯示由 方法傳 Round(Decimal, MidpointRounding) 回的值,其值有不同的 mode 值。

Console.WriteLine($"{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}");
for (decimal value = 12.0m; value <= 13.0m; value += 0.1m)
    Console.WriteLine($"{value,-10} {Math.Round(value),-10} " +
        $"{Math.Round(value, MidpointRounding.ToEven),-10} " +
        $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " +
        $"{Math.Round(value, MidpointRounding.ToZero),-15}");

// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12.0       12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13.0       13         13         13              13
printfn $"""{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}"""
for value in 12m .. 0.1m .. 13m do
    printfn "%-10O %-10O %-10O %-15O %-15O" 
        value
        (Math.Round value)
        (Math.Round(value, MidpointRounding.ToEven))
        (Math.Round(value, MidpointRounding.AwayFromZero))
        (Math.Round(value, MidpointRounding.ToZero))

// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12.0       12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13.0       13         13         13              13
Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}", "Value", "Default",
                "ToEven", "AwayFromZero", "ToZero")
For value As Decimal = 12D To 13D Step 0.1D
    Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}",
                   value, Math.Round(value),
                   Math.Round(value, MidpointRounding.ToEven),
                   Math.Round(value, MidpointRounding.AwayFromZero),
                   Math.Round(value, MidpointRounding.ToZero))
Next

' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero     ToZero
'       12         12         12         12               12
'       12.1       12         12         12               12
'       12.2       12         12         12               12
'       12.3       12         12         12               12
'       12.4       12         12         12               12
'       12.5       12         12         13               12
'       12.6       13         13         13               12
'       12.7       13         13         13               12
'       12.8       13         13         13               12
'       12.9       13         13         13               12
'       13.0       13         13         13               13

另請參閱

適用於