Math.Round 方法

定義

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

多載

名稱 Description
Round(Double, Int32, MidpointRounding)

利用指定的四捨五入慣例,將雙精度浮點數數四捨五入至指定數量的分數位數。

Round(Decimal, Int32, MidpointRounding)

利用指定的四捨五入慣例,將小數點數四捨五入至指定數量的分數。

Round(Double, MidpointRounding)

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

Round(Double, Int32)

將雙精度浮點數取整至指定小數位數,並將中點數取整至最近的偶數。

Round(Decimal, Int32)

將小數值四捨五入至指定小數位數,並將中點數四捨五入至最近的偶數。

Round(Double)

將雙精度浮點數取整至最近的整數值,並將中點數取入至最近的偶數。

Round(Decimal)

將小數值四捨五入為最近的整數值,並將中點值四捨五入至最近的偶數。

Round(Decimal, MidpointRounding)

使用指定的四捨五入約定,將小數值四捨五入整數。

範例

除了 備註 區的範例外,方法的每個超載 Math.Round 部分都有範例。

備註

本節內容:

我應該使用哪一種方法?

你可以使用下表來選擇合適的四捨五入方法。 除了這些方法外 Math.Round ,它還包含 Math.Ceiling 了 和 Math.Floor

Call
利用四捨五入至最近約定將數字四捨五入為整數。 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 標準 754,第 4 節。 在多次四捨五入運算中使用時,四捨五入至最近甚至可減少因持續在單一方向四捨五入中點值所造成的四捨五入誤差。 在某些情況下,這種四捨五入誤差可能相當顯著。

以下範例說明了持續將中點值在單一方向上四捨五入所產生的偏差。 範例先計算一組 Decimal 值的真實平均值,然後利用兩種慣例四捨五入後計算平均值。 在此範例中,真實平均值與四捨五入至最近的平均值相同。 然而,當從零四捨五入時,所得的平均值與真實平均相差 0.05(或 3.6%)。

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 方法的超載值以及各自使用的捨入慣例。

Overload 四捨五入慣例
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 是回傳值中所需的小數位數,然後判斷剩餘的分數值是否大於或等於 0.5。 這是相等檢定的一個小小變體,正如參考主題「相位測試」章節 Double 所討論的,浮點數值的相位檢定存在問題,因為浮點格式在二進位表示和精確度上存在問題。 這表示任何略小於 0.5 的小數部分(因精度損失)不會被向上取整。

下列範例說明問題。 它反覆將 0.1 加到 11.0,並將結果四捨五入至最接近的整數。 11.5 應利用中點四捨五入慣例ToEven (或 AwayFromZero)四捨五入為 12。 然而,正如範例所示,並非如此。 範例中使用「R」 標準數字格式字串 來顯示浮點數值的完整精度,並顯示待四捨五入的值在反覆加法過程中精度下降,實際上其值為 11.49999999999999998。 由於 .499999999999998 小於 0.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

中點值四捨五入的精度問題最可能出現在以下條件下:

  • 當某個分數值無法精確以浮點數型態的二進位格式表示時,
  • 當要四捨五入的值是透過一個或多個浮點運算計算得出時。
  • 當要四捨五入的值是 a 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四捨五入。 如果你將 Single 值傳給 Round 方法的超載,該值會在 C# 中被鑄造或在 Visual Basic 中轉換成 Double,並呼叫對應的 Round 過載,且參數為 Double。 雖然這是一種擴大轉換,但通常會失去精確度,如下範例所示。 當 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,因此總是向上取整。

在許多情況下,如範例所示,精度損失可以透過鑄造或轉換 SingleDecimal來最小化或消除。 請注意,由於這是一種狹窄轉換,因此需要使用鑄造運算子或呼叫轉換方法。

Round(Double, Int32, MidpointRounding)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 位。

有關用中點值四捨五入的資訊,請參見中 點值與四捨五 入慣例。

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

value 參數值為 Double.NaN,則方法回傳 Double.NaN。 若 valueDouble.PositiveInfinityDouble.NegativeInfinity,則該方法分別返回 Double.PositiveInfinityDouble.NegativeInfinity

範例

以下範例示範如何使用 Round(Double, Int32, MidpointRounding) 該方法與 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)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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範圍。

備註

有關用中點值四捨五入的資訊,請參見中 點值與四捨五 入慣例。

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

參數值 decimals 範圍可從0到28。

範例

以下範例示範如何使用 Round 該方法與 MidpointRounding 枚舉。

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)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 被四捨五入為。 此方法回傳 a Double 而非整數型。

例外狀況

mode 不是有效的值 MidpointRounding

備註

有關用中點值四捨五入的資訊,請參見中 點值與四捨五 入慣例。

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

value 參數值為 Double.NaN,則方法回傳 Double.NaN。 若 valueDouble.PositiveInfinityDouble.NegativeInfinity,則該方法分別返回 Double.PositiveInfinityDouble.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)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 有關用中點值四捨五入的資訊,請參見中 點值與四捨五 入慣例。

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

value 參數值為 Double.NaN,則方法回傳 Double.NaN。 若 valueDouble.PositiveInfinityDouble.NegativeInfinity,則該方法分別返回 Double.PositiveInfinityDouble.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
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)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 關於中點值的四捨五入資訊,請參見 中點值與四捨五入慣例

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

範例

以下範例將小數值分為兩位小數,四捨五入為單一小數位數值。

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)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 數分量介於兩個整數之間,其中一個為偶數,另一個為奇數,則返回偶數。 請注意,此方法回傳的 a Double 而非整數型別。

備註

此方法使用預設的四捨五入約定。MidpointRounding.ToEven 關於中點值的四捨五入資訊,請參見 中點值與四捨五入慣例

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

a 參數值為 Double.NaN,則方法回傳 Double.NaN。 若 aDouble.PositiveInfinityDouble.NegativeInfinity,則該方法分別返回 Double.PositiveInfinityDouble.NegativeInfinity

從 Visual Basic 15.8 開始,若將 Round 方法回傳的值傳遞給任一 積分轉換函式,或將 Round 回傳的 Double 值自動轉換為整數且 Option Strict 關閉,則會優化雙整數轉換的效能。 此最佳化可讓程式碼執行得更快,對於執行大量整數類型的程式碼,速度最高可達兩倍。 以下範例說明了此類最佳化轉換:

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

範例

以下範例示範將四捨五入至最接近的整數值。

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)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 數分量介於兩個整數之間,其中一個為偶數,另一個為奇數,則返回偶數。 請注意,此方法回傳的 a 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 關於中點值的四捨五入資訊,請參見 中點值與四捨五入慣例

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

另請參閱

適用於

Round(Decimal, MidpointRounding)

來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
Math.cs
來源:
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 被四捨五入為。 此方法回傳 a Decimal 而非整數型。

例外狀況

mode 不是有效的值 MidpointRounding

結果超出 的 Decimal範圍。

備註

關於中點值的四捨五入資訊,請參見 中點值與四捨五入慣例

Important

當四捨五入中點值時,四捨五入演算法會進行等式檢驗。 由於浮點數格式中二進位表示與精度的問題,該方法回傳的值可能出乎意料。 更多資訊請參見 四捨五入與精確度

範例

以下範例顯示方法回傳 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

另請參閱

適用於