閱讀英文版本

分享方式:


MidpointRounding 列舉

定義

指定數學捨入方法應該用來四捨五入數位的策略。

C#
public enum MidpointRounding
C#
[System.Runtime.InteropServices.ComVisible(true)]
public enum MidpointRounding
繼承
MidpointRounding
屬性

欄位

名稱 Description
AwayFromZero 1

四捨五入為最接近數位的策略,而當數位介於兩個數字之間的一半時,會四捨五入到最接近零的數位。

ToEven 0

四捨五入為最接近數位的策略,而當數位在兩個數字之間半角時,就會四捨五入到最接近的偶數。

ToNegativeInfinity 3

向下導向捨入的策略,其結果最接近且不大於無限精確的結果。

ToPositiveInfinity 4

向上導向捨入的策略,其結果最接近且不小於無限精確的結果。

ToZero 2

將四捨五入為零的策略,其結果最接近且大小不大於無限精確結果。

範例

下列範例示範 Math.Round 方法與 MidpointRounding 列舉:

C#
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)
*/

備註

如需此 API 的詳細資訊,請參閱 MidpointRounding 的補充 API 備註

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0