Math.Round Math.Round Math.Round Math.Round Method

Definition

最も近い整数または指定した小数点以下の桁数に値を丸めます。 Rounds a value to the nearest integer or to the specified number of fractional digits.

Overloads

Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding)

10 進値を、指定した小数部の桁数に丸めます。 Rounds a decimal value to a specified number of fractional digits. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding)

倍精度浮動小数点値を指定した小数部の桁数に丸めます。 Rounds a double-precision floating-point value to a specified number of fractional digits. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding)

倍精度浮動小数点値を最も近い整数に丸めます。 Rounds a double-precision floating-point value to the nearest integer. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

Round(Double, Int32) Round(Double, Int32) Round(Double, Int32) Round(Double, Int32)

倍精度浮動小数点値を指定した小数部の桁数に丸めます。 Rounds a double-precision floating-point value to a specified number of fractional digits.

Round(Double) Round(Double) Round(Double) Round(Double)

倍精度浮動小数点値を最も近い整数値に丸めます。 Rounds a double-precision floating-point value to the nearest integral value.

Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32)

10 進値を、指定した小数部の桁数に丸めます。 Rounds a decimal value to a specified number of fractional digits.

Round(Decimal) Round(Decimal) Round(Decimal) Round(Decimal)

10 進値を最も近い整数値に丸めます。 Rounds a decimal value to the nearest integral value.

Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding)

10 進値を最も近い整数に丸めます。 Rounds a decimal value to the nearest integer. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

Remarks

このセクションの内容:In this section:

オーバー ロードされたメソッドの構文 Overloaded method syntax
パラメーター Parameters
戻り値 Return value
例外 Exceptions
どのメソッドが呼び出しですか。 Which method do I call?
中間値と丸め規則 Midpoint values and rounding conventions
丸め処理や有効桁数 Rounding and precision
丸めと単精度浮動小数点値 Rounding and single-precision floating-point values
次に例を示します。Examples:
Math.Round(Decimal)Math.Round(Decimal)
Math.Round(Double)Math.Round(Double)
Math.Round (10 進数、int32 型)Math.Round(Decimal, Int32)
Math.Round (10 進数、MidpointRounding)Math.Round(Decimal, MidpointRounding)
Math.Round (Double、int32 型)Math.Round(Double, Int32)
Math.Round (Double MidpointRounding)Math.Round(Double, MidpointRounding)
Math.Round (10 進数、Int32、MidpointRounding)Math.Round(Decimal, Int32, MidpointRounding)
Math.Round (Double、Int32、MidpointRounding)Math.Round(Double, Int32, MidpointRounding)
バージョン情報Version information

オーバー ロードされたメソッドの構文Overloaded method syntax

オーバー ロードの選択に追加のガイダンスについては、次を参照してくださいどのメソッドが呼び出しですか?。For additional guidance on choosing an overload, see Which method do I call?

Decimal Math.Round(Decimal d )Decimal Math.Round(Decimal d )
10 進値を最も近い整数に丸めます、最も近い偶数に中間値を丸めます ()。Rounds a decimal value to the nearest integer, and rounds midpoint values to the nearest even number (example).

Double Math.Round(Double a )Double Math.Round(Double a )
最も近い整数、倍精度浮動小数点値を丸めます、最も近い偶数に中間値を丸めます ()。Rounds a double-precision floating-point value to the nearest integer, and rounds midpoint values to the nearest even number (example).

Decimal Math.Round(Decimal d , Int32 decimals )Decimal Math.Round(Decimal d , Int32 decimals )
指定した小数部の桁数の 10 進数値を四捨五入し、中間値を最も近い偶数の桁に丸めます ()。Rounds a decimal value to a specified number of fractional digits, and rounds midpoint values to the nearest even number (example).

Double Math.Round(Double value , Int32 digits )Double Math.Round(Double value , Int32 digits )
指定された数の小数部の桁数を倍精度浮動小数点値を丸めます、最も近い偶数に中間値を丸めます ()。Rounds a double-precision floating-point value to a specified number of fractional digits, and rounds midpoint values to the nearest even number (example).

Decimal Math.Round(Decimal d , MidpointRounding mode )Decimal Math.Round(Decimal d , MidpointRounding mode )
10 進値を最も近い整数に丸めます、中間値の指定した丸め規則を使用して ()。Rounds a decimal value to the nearest integer, and uses the specified rounding convention for midpoint values (example).

Double Math.Round(Double value , MidpointRounding mode )Double Math.Round(Double value , MidpointRounding mode )
最も近い整数、倍精度浮動小数点値を四捨五入し、中間値の指定した丸め規則を使用して ()。Rounds a double-precision floating-point value to the nearest integer, and uses the specified rounding convention for midpoint values (example).

Decimal Math.Round(Decimal d , Int32 decimals , MidpointRounding mode )Decimal Math.Round(Decimal d , Int32 decimals , MidpointRounding mode )
指定した小数部の桁数の 10 進値を四捨五入し、中間値の指定した丸め規則を使用して ()。Rounds a decimal value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values (example).

Double Math.Round(Double value , Int32 digits , MidpointRounding mode )Double Math.Round(Double value , Int32 digits , MidpointRounding mode )
指定した桁の小数部の倍精度浮動小数点値を四捨五入し、中間値の指定した丸め規則を使用して ()。Rounds a double-precision floating-point value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values (example).

パラメーターParameters

これは、パラメーターの完全な一覧、Roundメソッド。This is a complete list of parameters for the Round method. 各オーバー ロードによって使用されるパラメーター、上記のオーバー ロードの構文を参照してください。For the parameters used by each overload, see the overload syntax above.

パラメーターParameter Type 説明Description
d Decimal 丸め対象の数。A number to be rounded.
a

- または --or-

value
Double 丸め対象の倍精度浮動小数点数。A double-precision floating-point number to be rounded.
decimals

- または --or-

digits
Int32 戻り値の小数部の桁数。The number of fractional digits in the return value. Decimal値、その範囲は 0 から 28。For Decimal values, it can range from 0 to 28. Double値、その範囲は 0 を 15 にします。For Double values, it can range from 0 to 15. サポートされている整数部と小数桁の数字の最大数は、15、Double型。Note that 15 is the maximum number of integral and fractional digits supported by the Double type.

既定値: 0 で、整数に丸められますDefault value: 0, which rounds to an integer
mode MidpointRounding 中間の値を丸めるに使用する規則を指定するフラグ。A flag that specifies the convention to use for rounding midpoint values. 参照してください中間値と丸め規則します。See Midpoint values and rounding conventions.

既定値: MidpointRounding.ToEvenDefault value: MidpointRounding.ToEven

戻り値Return value

型:DecimalまたはDoubleを丸めた後の値の型に応じて、します。Type: Decimal or Double, depending on the type of the value to be rounded.
同じ型の数値da、またはvalue、整数または指定した 10 進数のいずれかが丸みのあります。A numeric value of the same type as d, a, or value, but rounded either to an integer or to the specified number of decimal digits. 参照してください中間値と丸め規則中間値を持つ数値丸め処理を行う方法についてはします。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

警告

中間値を丸め、丸め処理を行うアルゴリズムは、等値テストを実行します。When rounding midpoint values, the rounding algorithm performs an equality test. バイナリ表現と単精度浮動小数点形式での問題、原因は、メソッドによって返される値を予期できないことができます。Because of problems of binary representation and precision in the floating-point format, the value returned by the method can be unexpected. 詳細については、次を参照してください。丸めと有効桁数します。For more information, see Rounding and precision.

オーバー ロードの場合、Doubleパラメーターを使用して呼び出したDouble.NaN、メソッドを返しますDouble.NaNします。If an overload with a Double parameter is called with Double.NaN, the method returns Double.NaN. 使用して呼び出した場合Double.PositiveInfinityまたはDouble.NegativeInfinity、メソッドを返しますDouble.PositiveInfinityまたはDouble.NegativeInfinity、それぞれします。If it is called with Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

例外Exceptions

例外Exception 条件Condition によってスローされます。Thrown by
OverflowException 範囲外の結果は、Decimal型。The result is outside the range of the Decimal type. Round(Decimal)

Round(Decimal, Int32)

Round(Decimal, MidpointRounding)

Round(Decimal, Int32, MidpointRounding)
ArgumentOutOfRangeException decimals が 0 未満か、28 を超えています。decimals is less than 0 or greater than 28.

- または --or-

digits が 0 より小さいか、15 を超えています。digits is less than 0 or greater than 15.
Round(Decimal, Int32)

Round(Double, Int32)

Round(Decimal, Int32, MidpointRounding)

Round(Double, Int32, MidpointRounding)
ArgumentException mode が有効な MidpointRounding 値ではありません。mode is not a valid value of MidpointRounding. Round(Decimal, MidpointRounding)

Round(Double, MidpointRounding)

Round(Decimal, Int32, MidpointRounding)

Round(Double, Int32, MidpointRounding)

どのメソッドが呼び出しですか。Which method do I call?

終了To CallCall
最も近い規則への丸めを使用して整数に四捨五入します。Round a number to an integer by using the rounding to nearest convention. Round(Decimal)

- または --or-

Round(Double)
数値を指定したを使用して、整数丸め規則を丸め処理します。Round a number to an integer by using a specified rounding convention. Round(Decimal, MidpointRounding)

- または --or-

Round(Double, MidpointRounding)
最も近い規則への丸めを使用して指定した小数部の桁数に数値を丸めます。Round a number to a specified number of fractional digits by using the rounding to nearest convention. Round(Decimal, Int32)

- または --or-

Round(Double, Int32)
指定して、指定した小数部の桁数に数値を丸め、規則を丸めです。Round a number to a specified number of fractional digits by using a specified rounding convention. Round(Decimal, Int32, MidpointRounding)

- または --or-

Round(Double, Int32, MidpointRounding)
Round、Singleを指定した指定した丸め規則と有効桁数の損失を最小限に抑えることを使用して桁の小数部の値。Round a Single value to a specified number of fractional digits by using a specified rounding convention and minimizing the loss of precision. 変換、SingleDecimalを呼び出すとRound(Decimal, Int32, MidpointRounding)します。Convert the Single to a Decimal and call Round(Decimal, Int32, MidpointRounding).
中間の値を丸める有効桁数の問題を最小限に抑えながらを指定した小数部の桁の数値を丸めます。Round a number to a specified number of fractional digits while minimizing problems of precision in rounding midpoint values. 「より大きいまたはにほぼ等しい」比較を実装する丸め処理を行うメソッドを呼び出します。Call a rounding method that implements a "greater than or approximately equal to" comparison. 参照してください丸めと有効桁数します。See Rounding and precision.
円形の小数部の値を整数に小数部の値よりも大きいです。Round a fractional value to an integer that is greater than the fractional value. たとえば、3.1 を 4 に切り上げられます。For example, round 3.1 to 4. Ceiling
小数部の値を整数に丸めが小数部の値より小さいです。Round a fractional value to an integer that is less than the fractional value. たとえば、3.9 を 3 に切り上げられます。For example, round 3.9 to 3. Floor

中間値と丸め規則Midpoint values and rounding conventions

丸め処理を行うには、指定された有効桁数で数値を低精度の最も近い値に変換する必要があります。Rounding involves converting a numeric value with a specified precision to the nearest value with less precision. たとえば、使用することができます、 Round(Double) 3.4 と 3.0 の値を丸めるメソッドとRound(Double, Int32)3.579 に 3.58 の値を丸めます。For example, you can use the Round(Double) method to round a value of 3.4 to 3.0, and the Round(Double, Int32) method to round a value of 3.579 to 3.58.

中間値では、結果の最下位の数字の後の値は、2 つの数値の間で正確に半分方法です。In a midpoint value, the value after the least significant digit in the result is precisely half way between two numbers. たとえば、3.47500 は中間の値である場合に 2 つの小数点以下桁数が丸められます、7.500 中間値を整数に丸め 場合は、です。For example, 3.47500 is a midpoint value if it is to be rounded two decimal places, and 7.500 is a midpoint value if it is to be rounded to an integer. このような場合は、最も近い値は丸め規則なし簡単に識別することはできません。In these cases, the nearest value can't be easily identified without a rounding convention.

Roundメソッドは、中間値を処理するための 2 つの丸め規則をサポートしています。The Round method supports two rounding conventions for handling midpoint values:

ゼロから離れる方向に丸め処理Rounding away from zero
中間値は、次の番号をゼロから離れる方向に丸められます。Midpoint values are rounded to the next number away from zero. 次の例では、3.75 が 3.8 に四捨五入-3.8 に 3.9 に 3.85 ラウンド-3.75 が丸められ、-3.85-3.9 に桁に丸めます。For example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8, and -3.85 rounds to -3.9. この形式の丸めがによって表される、MidpointRounding.AwayFromZero列挙型のメンバー。This form of rounding is represented by the MidpointRounding.AwayFromZero enumeration member.

ゼロから離れる方向に丸め処理は、丸め処理の最もよく知られた形式です。Rounding away from zero is the most widely known form of rounding.

、近似値に丸め処理や銀行型丸めRounding to nearest, or banker's rounding
中間値は、最も近い偶数に丸められます。Midpoint values are rounded to the nearest even number. たとえば、3.75 と 3.85 の両方が 3.8 に丸める、-3.75 と-3.85 の両方が-3.8 に丸めます。For example, both 3.75 and 3.85 round to 3.8, and both -3.75 and -3.85 round to -3.8. この形式の丸めがによって表される、MidpointRounding.ToEven列挙型のメンバー。This form of rounding is represented by the MidpointRounding.ToEven enumeration member.

近似値に丸め処理は、財務や統計操作で使用される丸め処理の標準的な形式です。Rounding to nearest is the standard form of rounding used in financial and statistical operations. IEEE 標準 754、セクション 4 に準拠しています。It conforms to IEEE Standard 754, section 4. 複数の丸め処理で使用する場合、常に中間値を 1 つの方向に丸めるによって引き起こされる丸めエラーが減少します。When used in multiple rounding operations, it reduces the rounding error that is caused by consistently rounding midpoint values in a single direction. 場合によっては、この丸めエラーは大幅にできます。In some cases, this rounding error can be significant.

次の例は、常に中間値を 1 つの方向に丸めることができます、バイアスを示しています。The following example illustrates the bias that can result from consistently rounding midpoint values in a single direction. 配列の真の平均を計算する例では、Decimal値、および 2 つの規則を使用して、配列内の値が丸められたときに、平均を計算します。The example computes the true mean of an array of Decimal values, and then computes the mean when the values in the array are rounded by using the two conventions. この例では、真の平均と、平均の近似値に丸め処理を行うときに、結果は同じです。In this example, the true mean and the mean that results when rounding to nearest are the same. ただし、ゼロから離れる方向丸め処理を行うときに、結果、平均値とは異なる.05 (または 3.6%) 真の平均から。However, the mean that results when rounding away from zero differs by .05 (or by 3.6%) from the true mean.

using System;

public class Example
{
   public static void Main()
   {
      decimal[] values = { 1.15m, 1.25m, 1.35m, 1.45m, 1.55m, 1.65m };
      decimal sum = 0;
      
      // Calculate true mean.
      foreach (var value in values)
         sum += value;

      Console.WriteLine("True mean:     {0:N2}", sum/values.Length);
      
      // Calculate mean with rounding away from zero.
      sum = 0;
      foreach (var value in values)
         sum += Math.Round(value, 1, MidpointRounding.AwayFromZero);

      Console.WriteLine("AwayFromZero:  {0:N2}", sum/values.Length);
      
      // Calculate mean with rounding to nearest.
      sum = 0;
      foreach (var value in values)
         sum += Math.Round(value, 1, MidpointRounding.ToEven);

      Console.WriteLine("ToEven:        {0:N2}", sum/values.Length);
   }
}
// The example displays the following output:
//       True mean:     1.40
//       AwayFromZero:  1.45
//       ToEven:        1.40
Module Example
   Public Sub Main()
      Dim values() As Decimal = { 1.15d, 1.25d, 1.35d, 1.45d, 1.55d, 1.65d }
      Dim sum As Decimal
      
      ' Calculate true mean.
      For Each value In values
         sum += value
      Next
      Console.WriteLine("True mean:     {0:N2}", sum/values.Length)
      
      ' Calculate mean with rounding away from zero.
      sum = 0
      For Each value In values
         sum += Math.Round(value, 1, MidpointRounding.AwayFromZero)
      Next
      Console.WriteLine("AwayFromZero:  {0:N2}", sum/values.Length)
      
      ' Calculate mean with rounding to nearest.
      sum = 0
      For Each value In values
         sum += Math.Round(value, 1, MidpointRounding.ToEven)
      Next
      Console.WriteLine("ToEven:        {0:N2}", sum/values.Length)
   End Sub
End Module
' The example displays the following output:
'       True mean:     1.40
'       AwayFromZero:  1.45
'       ToEven:        1.40

既定で、Roundメソッドは、最も近い規則に丸めを使用します。By default, the Round method uses the rounding to nearest convention. 次の表のオーバー ロード、Roundメソッドと、丸め規則それぞれの使用します。The following table lists the overloads of the Round method and the rounding convention that each uses.

オーバーロードOverload 規則の丸め処理を行うRounding convention
Round(Decimal) ToEven
Round(Double) ToEven
Round(Decimal, Int32) ToEven
Round(Double, Int32) ToEven
Round(Decimal, MidpointRounding) によって決定modeパラメーター。Determined by mode parameter.
Round(Double, MidpointRounding) によって決定modeパラメーターDetermined by mode parameter
Round(Decimal, Int32, MidpointRounding) によって決定modeパラメーターDetermined by mode parameter
Round(Double, Int32, MidpointRounding) によって決定modeパラメーターDetermined by mode parameter

丸め処理や有効桁数Rounding and precision

丸め操作を中間値は、かどうかを判断するために、Roundメソッドは元の値が 10 で切り捨てられます、乗算nここで、 n小数部の桁数は、戻り値、数字、値の小数部から成る残りの部分が.5 以上かどうかを判断します。In order to determine whether a rounding operation involves a midpoint value, the Round method multiplies the original value to be rounded by 10n, where n is the desired number of fractional digits in the return value, and then determines whether the remaining fractional portion of the value is greater than or equal to .5. これは、若干のバリエーションの「テストの等価性」セクションでテストし、等しいかどうか、で説明したように、Doubleリファレンス トピックでは、テスト浮動小数点値と等しいかどうかは問題のあるバイナリ浮動小数点形式問題が原因形式と有効桁数。This is a slight variation on a test for equality, and as discussed in the "Testing for Equality" section of the Double reference topic, tests for equality with floating-point values are problematic because of the floating-point format's issues with binary representation and precision. これは、こと (精度が低下する) ため .5 より若干小さい数値の任意の小数部は丸められません上方向を意味します。This means that any fractional portion of a number that is slightly less than .5 (because of a loss of precision) will not be rounded upward.

この問題を説明する例を次に示します。The following example illustrates the problem. 繰り返し、.1 に 11.0 を追加し、結果を最も近い整数に丸めます。It repeatedly adds .1 to 11.0 and rounds the result to the nearest integer. 丸めの規則に関係なく 11.5 は 12 に丸める必要があります。Regardless of the rounding convention, 11.5 should round to 12. ただし、例の出力として存在しません。However, as the output from the example shows, it does not. 例では、"R"を使用して標準数値書式指定文字列表示には、値の完全な有効桁数、および値は切り捨てられますが、繰り返しの追加中に有効桁数を失ったことを示しています、浮動小数点し、その値が実際には11.499999999999998 します。The example uses the "R" standard numeric format string to display the floating point value's full precision, and shows that the value to be rounded has lost precision during repeated additions, and its value is actually 11.499999999999998. .499999999999998.5 未満であるため、値は [次へ] の最大の整数に丸められません。Because .499999999999998 is less than .5, the value is not rounded to the next highest integer. 定数の値に対して 11.5 に割り当てるだけですがある場合、例に示すことも、この問題は発生しません、Double変数。As the example also shows, this problem does not occur if we simply assign the constant value 11.5 to a Double variable.

using System;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n", 
                        "Value", "Full Precision", "ToEven",
                        "AwayFromZero");
      double value = 11.1;
      for (int ctr = 0; ctr <= 5; ctr++)    
         value = RoundValueAndAdd(value);

      Console.WriteLine();

      value = 11.5;
      RoundValueAndAdd(value);
   }
   
   private static double RoundValueAndAdd(double value)
   {
      Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                        value, Math.Round(value, MidpointRounding.ToEven),
                        Math.Round(value, MidpointRounding.AwayFromZero));
      return value + .1;
   }
}
// The example displays the following output:
//       Value       Full Precision        ToEven    AwayFromZero
//       
//        11.1                 11.1            11              11
//        11.2                 11.2            11              11
//        11.3   11.299999999999999            11              11
//        11.4   11.399999999999999            11              11
//        11.5   11.499999999999998            11              11
//        11.6   11.599999999999998            12              12
//       
//        11.5                 11.5            12              12
Module Example
   Public Sub Main()
      Dim value As Double = 11.1

      Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}", 
                        "Value", "Full Precision", "ToEven",
                        "AwayFromZero")
      Console.WriteLine()
      For ctr As Integer = 0 To 5    
         value = RoundValueAndAdd(value)
      Next
      Console.WriteLine()

      value = 11.5
      RoundValueAndAdd(value)
   End Sub
   
   Private Function RoundValueAndAdd(value As Double) As Double
      Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                        value, Math.Round(value, MidpointRounding.ToEven),
                        Math.Round(value, MidpointRounding.AwayFromZero))
      Return value + .1
   End Function   
End Module
' The example displays the following output:
'       Value       Full Precision        ToEven    AwayFromZero
'       
'        11.1                 11.1            11              11
'        11.2                 11.2            11              11
'        11.3   11.299999999999999            11              11
'        11.4   11.399999999999999            11              11
'        11.5   11.499999999999998            11              11
'        11.6   11.599999999999998            12              12
'       
'        11.5                 11.5            12              12

中間の値を丸める有効桁数の問題は、次の条件で発生する可能性が高いです。Problems of precision in rounding midpoint values are most likely to arise in the following conditions:

  • ときに小数部の値は、浮動小数点型のバイナリ形式で正確に表現できません。When a fractional value cannot be expressed precisely in the floating-point type's binary format.

  • ときに値が切り捨てられますが、1 つまたは複数の浮動小数点演算から計算されます。When the value to be rounded is calculated from one or more floating-point operations.

  • 丸め対象の値が、SingleなくDoubleまたはDecimalします。When the value to be rounded is a Single rather than a Double or Decimal. 詳細については、次のセクションを参照してください。丸めと単精度浮動小数点値します。For more information, see the next section, Rounding and single-precision floating-point values.

操作を丸める有効桁数が不足しているが問題のある場合には、次の操作を行うことができます。In cases where the lack of precision in rounding operations is problematic, you can do the following:

  • 丸め演算が四捨五入するオーバー ロードを呼び出す場合、Double値を変更できます、DoubleDecimal値し、四捨五入するオーバー ロードを呼び出して、Decimal値の代わりにします。If the rounding operation calls an overload that rounds a Double value, you can change the Double to a Decimal value and call an overload that rounds a Decimal value instead. ただし、Decimalデータ型は、有効桁数の損失と表現の問題にもが、これらの問題は、はるかにまれです。Although the Decimal data type also has problems of representation and loss of precision, these issues are far less common.

  • 中間値に近い値は切り捨てられますが期待がかどうかを判断する「ほぼ等しい」テストを実行するカスタムの丸め処理を行うアルゴリズムを定義します。Define a custom rounding algorithm that performs a "nearly equal" test to determine whether the value to be rounded is acceptably close to a midpoint value. 次の例では、定義、RoundApproximate小数部の値は、十分に中間丸め処理の対象に中間値の近くにあるかどうかを検査するメソッド。The following example defines a RoundApproximate method that examines whether a fractional value is sufficiently near to a midpoint value to be subject to midpoint rounding. 例の出力が示すように、前の例に示すように丸めの問題を修正します。As the output from the example shows, it corrects the rounding problem shown in the previous example.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n", 
                            "Value", "Full Precision", "ToEven",
                            "AwayFromZero");
          double value = 11.1;
          for (int ctr = 0; ctr <= 5; ctr++)    
             value = RoundValueAndAdd(value);
    
          Console.WriteLine();
    
          value = 11.5;
          RoundValueAndAdd(value);
       }
       
       private static double RoundValueAndAdd(double value)
       {
          const double tolerance = 8e-14;
    
          Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                            value, 
                            RoundApproximate(value, 0, tolerance, MidpointRounding.ToEven),
                            RoundApproximate(value, 0, tolerance, MidpointRounding.AwayFromZero));
          return value + .1;
       }
    
       private static double RoundApproximate(double dbl, int digits, double margin, 
                                         MidpointRounding mode)
       {                                      
          double fraction = dbl * Math.Pow(10, digits);
          double value = Math.Truncate(fraction); 
          fraction = fraction - value;   
          if (fraction == 0)
             return dbl;
          
          double tolerance = margin * dbl;
          // Determine whether this is a midpoint value.
          if ((fraction >= .5 - tolerance) & (fraction <= .5 + tolerance)) {
             if (mode == MidpointRounding.AwayFromZero)
                return (value + 1)/Math.Pow(10, digits);
             else
                if (value % 2 != 0)
                   return (value + 1)/Math.Pow(10, digits);
                else
                   return value/Math.Pow(10, digits);
          }
          // Any remaining fractional value greater than .5 is not a midpoint value.
          if (fraction > .5)
             return (value + 1)/Math.Pow(10, digits);
          else
             return value/Math.Pow(10, digits);
       }
    }
    // The example displays the following output:
    //       Value       Full Precision        ToEven    AwayFromZero
    //       
    //        11.1                 11.1            11              11
    //        11.2                 11.2            11              11
    //        11.3   11.299999999999999            11              11
    //        11.4   11.399999999999999            11              11
    //        11.5   11.499999999999998            12              12
    //        11.6   11.599999999999998            12              12
    //       
    //        11.5                 11.5            12              12
    
    Module Example
       Public Sub Main()
          Dim value As Double = 11.1
    
          Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n", 
                            "Value", "Full Precision", "ToEven",
                            "AwayFromZero")
          For ctr As Integer = 0 To 5    
             value = RoundValueAndAdd(value)
          Next
          Console.WriteLine()
    
          value = 11.5
          RoundValueAndAdd(value)
       End Sub
       
       Private Function RoundValueAndAdd(value As Double) As Double
          Const tolerance As Double = 8e-14
          Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}", 
                            value, 
                            RoundApproximate(value, 0, tolerance, MidpointRounding.ToEven),
                            RoundApproximate(value, 0, tolerance, MidpointRounding.AwayFromZero))
          Return value + .1
       End Function   
    
       Private Function RoundApproximate(dbl As Double, digits As Integer, margin As Double, 
                                         mode As MidpointRounding) As Double
          Dim fraction As Double = dbl * Math.Pow(10, digits)
          Dim value As Double = Math.Truncate(fraction) 
          fraction = fraction - value   
          If fraction = 0 Then Return dbl
          
          Dim tolerance As Double = margin * dbl
          ' Determine whether this is a midpoint value.
          If (fraction >= .5 - tolerance) And (fraction <= .5 + tolerance) Then
             If mode = MidpointRounding.AwayFromZero Then
                Return (value + 1)/Math.Pow(10, digits)
             Else
                If value Mod 2 <> 0 Then
                   Return (value + 1)/Math.Pow(10, digits)
                Else
                   Return value/Math.Pow(10, digits)
                End If
             End If
          End If
          ' Any remaining fractional value greater than .5 is not a midpoint value.
          If fraction > .5 Then
             Return (value + 1)/Math.Pow(10, digits)
          Else
             return value/Math.Pow(10, digits)
          End If      
       End Function
    End Module
    ' The example displays the following output:
    '       Value       Full Precision        ToEven    AwayFromZero
    '       
    '        11.1                 11.1            11              11
    '        11.2                 11.2            11              11
    '        11.3   11.299999999999999            11              11
    '        11.4   11.399999999999999            11              11
    '        11.5   11.499999999999998            12              12
    '        11.6   11.599999999999998            12              12
    '       
    '        11.5                 11.5            12              12
    

丸めと単精度浮動小数点値Rounding and single-precision floating-point values

Roundメソッドには、型の引数を受け入れるオーバー ロードが含まれています。DecimalDoubleします。The Round method includes overloads that accept arguments of type Decimal and Double. 型の値を丸めるメソッドがないSingleします。There are no methods that round values of type Single. 渡す場合、Singleのオーバー ロードのいずれかに値、Roundキャスト (c#) は、メソッド、または変換 (Visual Basic) で、 Double、および対応するRoundオーバー ロードをDoubleパラメーターと呼びます。If you pass a Single value to one of the overloads of the Round method, it is cast (in C#) or converted (in Visual Basic) to a Double, and the corresponding Round overload with a Double parameter is called. 拡大変換ですが、多くの場合が、精度の損失次の例に示すようにします。Although this is a widening conversion, it often involves a loss of precision, as the following example illustrates. ときに、Singleに 16.325 の値が渡される、Roundメソッドされ、結果は 16.32 の 16.33、いない期待される結果を最も近い規則への丸めを使用して 2 つの小数点以下桁数に丸められます、します。When a Single value of 16.325 is passed to the Round method and rounded to two decimal places using the rounding to nearest convention, the result is 16.33 and not the expected result of 16.32.

using System;

public class Example
{
   public static void Main()
   {
      Single value = 16.325f;
      Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", 
                        value, value.GetType().Name, (double) value, 
                        ((double) (value)).GetType().Name);
      Console.WriteLine(Math.Round(value, 2));
      Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero));
      Console.WriteLine();
      
      Decimal decValue = (decimal) value;
      Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ", 
                        value, value.GetType().Name, decValue, 
                        decValue.GetType().Name);
      Console.WriteLine(Math.Round(decValue, 2));
      Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero));
   }
}
// The example displays the following output:
//    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
//    16.33
//    16.33
//    
//    Cast of 16.325 (type Single) to 16.325 (type Decimal):
//    16.32
//    16.33
Module Example
   Public Sub Main()
      Dim value As Single = 16.325
      Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", 
                        value, value.GetType().Name, CDbl(value), 
                        CDbl(value).GetType().Name)
      Console.WriteLine(Math.Round(value, 2))
      Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero))
      Console.WriteLine()
      
      Dim decValue As Decimal = CDec(value)
      Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ", 
                        value, value.GetType().Name, decValue, 
                        decValue.GetType().Name)
      Console.WriteLine(Math.Round(decValue, 2))
      Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero))
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
'    16.33
'    16.33
'    
'    Cast of 16.325 (type Single) to 16.325 (type Decimal):
'    16.32
'    16.33

この予期しない結果での変換で精度の損失、Single値をDoubleします。This unexpected result is due to a loss of precision in the conversion of the Single value to a Double. その結果Doubleは上方向に丸められます常に、16.325000762939453 の値の中間値でないし、16.325 より大きい。Because the resulting Double value of 16.325000762939453 is not a midpoint value and is greater than 16.325, it is always rounded upward.

多くの場合、例に示すように、有効桁数の損失を最小限に抑えるしたり、キャストまたは変換で排除、Single値をDecimalします。In many cases, as the example illustrates, the loss of precision can be minimized or eliminated by casting or converting the Single value to a Decimal. 、これは、縮小変換であるため、必要があること、キャスト演算子を使用して、または変換メソッドを呼び出すことに注意してください。Note that, because this is a narrowing conversion, it requires using a cast operator or calling a conversion method.

Math.Round(Decimal) 例Math.Round(Decimal) example

次の例で、Round(Decimal)メソッド。The following example demonstrates the Round(Decimal) method. なお、Decimalこのオーバー ロードは既定値を使用するため、4.5 の値が 5 ではなく 4 に丸められますToEven規則。Note that the Decimal value of 4.5 rounds to 4 rather than 5, because this overload uses the default ToEven convention.

using System;

class Example
{
   static void Main()
   {
      for (decimal value = 4.2m; value <= 4.8m; value+=.1m )
         Console.WriteLine("{0} --> {1}", value, Math.Round(value));
   }
}
// The example displays the following output:
//       4.2 --> 4
//       4.3 --> 4
//       4.4 --> 4
//       4.5 --> 4
//       4.6 --> 5
//       4.7 --> 5
//       4.8 --> 5
Module Example
   Public Sub Main()
      For value As Decimal = 4.2d To 4.8d Step .1d
         Console.WriteLine("{0} --> {1}", value, Math.Round(value))
      Next   
   End Sub                                                                 
End Module
' The example displays the following output:
'       4.2 --> 4
'       4.3 --> 4
'       4.4 --> 4
'       4.5 --> 4
'       4.6 --> 5
'       4.7 --> 5
'       4.8 --> 5

Math.Round(Double) 例Math.Round(Double) example

次の例では、最も近い整数に丸め処理を示します。The following example demonstrates rounding to the nearest integer value.

using namespace System;

void main()
{
    Console::WriteLine("Classic Math.Round in CPP");
    Console::WriteLine(Math::Round(4.4));     // 4
    Console::WriteLine(Math::Round(4.5));     // 4
    Console::WriteLine(Math::Round(4.6));     // 5
    Console::WriteLine(Math::Round(5.5));     // 6
}
using System;

class Program
{
    static void Main()
    {
    Console.WriteLine("Classic Math.Round in CSharp");
    Console.WriteLine(Math.Round(4.4)); // 4
    Console.WriteLine(Math.Round(4.5)); // 4
    Console.WriteLine(Math.Round(4.6)); // 5
    Console.WriteLine(Math.Round(5.5)); // 6
    }
}
Imports System

Module Module1

    Sub Main()
    Console.WriteLine("Classic Math.Round in Visual Basic")
    Console.WriteLine(Math.Round(4.4)) ' 4
    Console.WriteLine(Math.Round(4.5)) ' 4
    Console.WriteLine(Math.Round(4.6)) ' 5
    Console.WriteLine(Math.Round(5.5)) ' 6
    End Sub

End Module

Math.Round (10 進数, Int32) の例Math.Round(Decimal, Int32) example

次の例では、2 桁の小数部を 1 つの桁の小数部を持つ値を含む 10 進数値を丸めます。The following example rounds decimal values with two fractional digits to values that have a single fractional digit.

using System;

public class Sample {
   static void Main() {
      Console.WriteLine(Math.Round(3.44m, 1)); 
      Console.WriteLine(Math.Round(3.45m, 1)); 
      Console.WriteLine(Math.Round(3.46m, 1)); 
      Console.WriteLine();
      
      Console.WriteLine(Math.Round(4.34m, 1)); 
      Console.WriteLine(Math.Round(4.35m, 1)); 
      Console.WriteLine(Math.Round(4.36m, 1)); 
   }
}
// The example displays the following output:
//       3.4
//       3.4
//       3.5
//       
//       4.3
//       4.4
//       4.4
Public Module Example
   Sub Main()
      Console.WriteLine(Math.Round(3.44, 1)) 
      Console.WriteLine(Math.Round(3.45, 1)) 
      Console.WriteLine(Math.Round(3.46, 1)) 
      Console.WriteLine()
      
      Console.WriteLine(Math.Round(4.34, 1)) 
      Console.WriteLine(Math.Round(4.35, 1)) 
      Console.WriteLine(Math.Round(4.36, 1)) 
   End Sub  
End Module
' The example displays the following output:
'       3.4
'       3.4
'       3.5
'       
'       4.3
'       4.4
'       4.4

Math.Round (Double、int32 型) の例Math.Round(Double, Int32) example

次の例では、2 桁の小数部を 1 つの桁の小数部が double 型の double 値を丸めます。The following example rounds double values with two fractional digits to doubles that have a single fractional digit.

Math::Round(3.44, 1); //Returns 3.4.
Math::Round(3.45, 1); //Returns 3.4.
Math::Round(3.46, 1); //Returns 3.5.

Math::Round(4.34, 1); // Returns 4.3
Math::Round(4.35, 1); // Returns 4.4
Math::Round(4.36, 1); // Returns 4.4
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.

Math.Round(4.34, 1); // Returns 4.3
Math.Round(4.35, 1); // Returns 4.4
Math.Round(4.36, 1); // Returns 4.4
Math.Round(3.44, 1) 'Returns 3.4.
Math.Round(3.45, 1) 'Returns 3.4.
Math.Round(3.46, 1) 'Returns 3.5.

Math.Round(4.34, 1) ' Returns 4.3
Math.Round(4.35, 1) ' Returns 4.4
Math.Round(4.36, 1) ' Returns 4.4

Math.Round (10 進数、MidpointRounding) の例Math.Round(Decimal, MidpointRounding) example

次の例は、によって返される値を表示、Round(Decimal)メソッド、Round(Decimal, MidpointRounding)メソッドをmodeの引数ToEven、およびRound(Decimal, MidpointRounding)メソッドをmodeの引数AwayFromZeroThe following example displays values returned by the Round(Decimal) method, the Round(Decimal, MidpointRounding) method with a mode argument of ToEven, and the Round(Decimal, MidpointRounding) method with a mode argument of AwayFromZero.

using System;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero");
      for (decimal value = 12.0m; value <= 13.0m; value += 0.1m)
         Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero));
   }
}
// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero
//       12         12         12         12
//       12.1       12         12         12
//       12.2       12         12         12
//       12.3       12         12         12
//       12.4       12         12         12
//       12.5       12         12         13
//       12.6       13         13         13
//       12.7       13         13         13
//       12.8       13         13         13
//       12.9       13         13         13
//       13.0       13         13         13
Module Example
   Public Sub Main()
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero")
      For value As Decimal = 12.0d To 13.0d Step .1d
         Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero))
      Next
   End Sub
End Module
' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero
'       12         12         12         12
'       12.1       12         12         12
'       12.2       12         12         12
'       12.3       12         12         12
'       12.4       12         12         12
'       12.5       12         12         13
'       12.6       13         13         13
'       12.7       13         13         13
'       12.8       13         13         13
'       12.9       13         13         13
'       13.0       13         13         13

Math.Round (Double MidpointRounding) の例Math.Round(Double, MidpointRounding) example

次の例は、によって返される値を表示、Round(Double)メソッド、Round(Double, MidpointRounding)メソッドをmodeの引数ToEven、およびRound(Double, MidpointRounding)メソッドをmodeの引数AwayFromZeroThe following example displays values returned by the Round(Double) method, the Round(Double, MidpointRounding) method with a mode argument of ToEven, and the Round(Double, MidpointRounding) method with a mode argument of AwayFromZero.

using System;

public class Example
{
   public static void Main()
   {
      Double[] values = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 
                          12.7, 12.8, 12.9, 13.0 };
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero");
      foreach (var value in values)
         Console.WriteLine("{0,-10:R} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero));
   }
}
// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero
//       12         12         12         12
//       12.1       12         12         12
//       12.2       12         12         12
//       12.3       12         12         12
//       12.4       12         12         12
//       12.5       12         12         13
//       12.6       13         13         13
//       12.7       13         13         13
//       12.8       13         13         13
//       12.9       13         13         13
//       13.0       13         13         13
Module Example
   Public Sub Main()
      Dim values() As Double = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 
                                 12.7, 12.8, 12.9, 13.0 }
      Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}", "Value", "Default", 
                        "ToEven", "AwayFromZero")
      For Each value In values
         Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15}",
                           value, Math.Round(value), 
                           Math.Round(value, MidpointRounding.ToEven),
                           Math.Round(value, MidpointRounding.AwayFromZero))
      Next
   End Sub
End Module
' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero
'       12         12         12         12
'       12.1       12         12         12
'       12.2       12         12         12
'       12.3       12         12         12
'       12.4       12         12         12
'       12.5       12         12         13
'       12.6       13         13         13
'       12.7       13         13         13
'       12.8       13         13         13
'       12.9       13         13         13
'       13.0       13         13         13

Math.Round (10 進数、Int32、MidpointRounding) の例Math.Round(Decimal, Int32, MidpointRounding) example

次の例では、使用する方法、RoundメソッドをMidpointRounding列挙体。The following example demonstrates how to use the Round method with the MidpointRounding enumeration.

// This example demonstrates the Math.Round() method in conjunction 
// with the MidpointRounding enumeration.
using namespace System;

void main()
{
    Decimal result = (Decimal) 0.0;
    Decimal posValue = (Decimal) 3.45;
    Decimal negValue = (Decimal) -3.45;

    // By default, round a positive and a negative value to the nearest
    // even number. The precision of the result is 1 decimal place.
    result = Math::Round(posValue, 1);
    Console::WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue);
    result = Math::Round(negValue, 1);
    Console::WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue);
    Console::WriteLine();

    // Round a positive value to the nearest even number, then to the
    // nearest number away from zero. The precision of the result is 1
    // decimal place.
    result = Math::Round(posValue, 1, MidpointRounding::ToEven);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
        result, posValue);
    result = Math::Round(posValue, 1, MidpointRounding::AwayFromZero);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
        result, posValue);
    Console::WriteLine();

    // Round a negative value to the nearest even number, then to the
    // nearest number away from zero. The precision of the result is 1
    // decimal place.
    result = Math::Round(negValue, 1, MidpointRounding::ToEven);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
        result, negValue);
    result = Math::Round(negValue, 1, MidpointRounding::AwayFromZero);
    Console::WriteLine(
        "{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
        result, negValue);
    Console::WriteLine();
}

/*
This code example produces the following results:

3.4 = Math.Round( 3.45, 1)
-3.4 = Math.Round(-3.45, 1)

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

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

*/
// This example demonstrates the Math.Round() method in conjunction 
// with the MidpointRounding enumeration.
using System;

class Sample 
{
    public static void Main() 
    {
    decimal result = 0.0m;
    decimal posValue =  3.45m;
    decimal negValue = -3.45m;

// By default, round a positive and a negative value to the nearest even number. 
// The precision of the result is 1 decimal place.

    result = Math.Round(posValue, 1);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue);
    result = Math.Round(negValue, 1);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue);
    Console.WriteLine();

// Round a positive value to the nearest even number, then to the nearest number away from zero. 
// The precision of the result is 1 decimal place.

    result = Math.Round(posValue, 1, MidpointRounding.ToEven);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", result, posValue);
    result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", result, posValue);
    Console.WriteLine();

// Round a negative value to the nearest even number, then to the nearest number away from zero. 
// The precision of the result is 1 decimal place.

    result = Math.Round(negValue, 1, MidpointRounding.ToEven);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", result, negValue);
    result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", result, negValue);
    Console.WriteLine();
    }
}
/*
This code example produces the following results:

 3.4 = Math.Round( 3.45, 1)
-3.4 = Math.Round(-3.45, 1)

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

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

*/
' This example demonstrates the Math.Round() method in conjunction 
' with the MidpointRounding enumeration.
Imports System

Class Sample
    Public Shared Sub Main() 
        Dim result As Decimal = 0D
        Dim posValue As Decimal = 3.45D
        Dim negValue As Decimal = -3.45D
        
        ' By default, round a positive and a negative value to the nearest even number. 
        ' The precision of the result is 1 decimal place.
        result = Math.Round(posValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue)
        result = Math.Round(negValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue)
        Console.WriteLine()
        
        ' Round a positive value to the nearest even number, then to the nearest number 
        ' away from zero. The precision of the result is 1 decimal place.
        result = Math.Round(posValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", _
                           result, posValue)
        result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", _
                           result, posValue)
        Console.WriteLine()
        
        ' Round a negative value to the nearest even number, then to the nearest number 
        ' away from zero. The precision of the result is 1 decimal place.
        result = Math.Round(negValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", _
                            result, negValue)
        result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", _
                           result, negValue)
        Console.WriteLine()
    
    End Sub 'Main
End Class 'Sample
'
'This code example produces the following results:
'
' 3.4 = Math.Round( 3.45, 1)
'-3.4 = Math.Round(-3.45, 1)
'
' 3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
' 3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
'
'-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
'-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
'

Math.Round (Double、Int32、MidpointRounding) の例Math.Round(Double, Int32, MidpointRounding) example

次の例では、使用する方法、Round(Double, Int32, MidpointRounding)メソッドをMidpointRounding列挙体。The following example demonstrates how to use the Round(Double, Int32, MidpointRounding) method with the MidpointRounding enumeration.

using System;

class Sample 
{
    public static void Main() 
    {
       double posValue =  3.45;
       double negValue = -3.45;

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

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

       // Round a negative value using a MidpointRounding value. 
       result = Math.Round(negValue, 1, MidpointRounding.ToEven);
       Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                         result, negValue);
       result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero);
       Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)\n", 
                         result, negValue);
   }
}
// The example displays the following output:
//        3.4 = Math.Round( 3.45, 1)
//       -3.4 = Math.Round(-3.45, 1)
//       
//        3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
//        3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
//       
//       -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
//       -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
Module Example
    Public Sub Main() 
        Dim posValue As Double = 3.45
        Dim negValue As Double = -3.45
        
        ' Round a positive and a negative value using the default.  
        Dim result As Double = Math.Round(posValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue)
        result = Math.Round(negValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue)
        Console.WriteLine()
        
        ' Round a positive value using a MidpointRounding value. 
        result = Math.Round(posValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                           result, posValue)
        result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", 
                           result, posValue)
        Console.WriteLine()
        
        ' Round a positive value using a MidpointRounding value. 
        result = Math.Round(negValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", 
                            result, negValue)
        result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", 
                           result, negValue)
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'       3.4 = Math.Round( 3.45, 1)
'       -3.4 = Math.Round(-3.45, 1)
'       
'       3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
'       3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
'       
'       -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
'       -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)

バージョン情報Version information

.NET Framework.NET Framework
なしのオーバー ロードをMidpointRoundingでパラメーターがサポートされています: 4.5、4、3.5、3.0、2.0、1.1、1.0Overloads without a MidpointRounding parameter are supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
オーバー ロードをMidpointRoundingでパラメーターがサポートされています: 4.5、4、3.5、3.0、2.0Overloads with a MidpointRounding parameter are supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile.NET Framework Client Profile
すべてのオーバー ロードではサポートされて: 4、3.5 SP1All overloads are supported in: 4, 3.5 SP1

ポータブル クラス ライブラリPortable Class Library
すべてのオーバー ロードがサポートされていますAll overloads are supported

Windows ストア アプリ用 .NET.NET for Windows Store apps
すべてのオーバー ロードがサポートされています: Windows 8All overloads are supported in: Windows 8

Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding) Round(Decimal, Int32, MidpointRounding)

10 進値を、指定した小数部の桁数に丸めます。 Rounds a decimal value to a specified number of fractional digits. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

public:
 static System::Decimal Round(System::Decimal d, int decimals, MidpointRounding mode);
public static decimal Round (decimal d, int decimals, MidpointRounding mode);
static member Round : decimal * int * MidpointRounding -> decimal
Public Shared Function Round (d As Decimal, decimals As Integer, mode As MidpointRounding) As Decimal

パラメーター

d
Decimal Decimal Decimal Decimal

丸め対象の 10 進数。 A decimal number to be rounded.

decimals
Int32 Int32 Int32 Int32

戻り値の小数部の桁数。 The number of decimal places in the return value.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

d が 2 つの数値の中間にある場合に丸める方法を指定します。 Specification for how to round d if it is midway between two other numbers.

Returns

d に等しい小数部の桁数を格納する decimals に最も近い数値。 The number nearest to d that contains a number of fractional digits equal to decimals. d の小数部の桁数が decimals よりも少ない場合、d がそのまま返されます。 If d has fewer fractional digits than decimals, d is returned unchanged.

Exceptions

decimals が 0 未満か、28 を超えています。 decimals is less than 0 or greater than 28.

mode が有効な MidpointRounding 値ではありません。 mode is not a valid value of MidpointRounding.

結果が Decimal の範囲外です。 The result is outside the range of a Decimal.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

See Also

Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding) Round(Double, Int32, MidpointRounding)

倍精度浮動小数点値を指定した小数部の桁数に丸めます。 Rounds a double-precision floating-point value to a specified number of fractional digits. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

public:
 static double Round(double value, int digits, MidpointRounding mode);
public static double Round (double value, int digits, MidpointRounding mode);
static member Round : double * int * MidpointRounding -> double
Public Shared Function Round (value As Double, digits As Integer, mode As MidpointRounding) As Double

パラメーター

value
Double Double Double Double

丸め対象の倍精度浮動小数点数。 A double-precision floating-point number to be rounded.

digits
Int32 Int32 Int32 Int32

戻り値の小数部の桁数。 The number of fractional digits in the return value.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

value が 2 つの数値の中間にある場合に丸める方法を指定します。 Specification for how to round value if it is midway between two other numbers.

Returns

digits に等しい小数部の桁数を格納する value に最も近い数値。 The number nearest to value that has a number of fractional digits equal to digits. value の小数部の桁数が digits よりも少ない場合、value がそのまま返されます。 If value has fewer fractional digits than digits, value is returned unchanged.

Exceptions

digits が 0 より小さいか、15 を超えています。 digits is less than 0 or greater than 15.

mode が有効な MidpointRounding 値ではありません。 mode is not a valid value of MidpointRounding.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

Notes to Callers

結果を浮動小数点数としての 10 進数の値を表すまたは場合によっては、浮動小数点値に対する算術演算を実行する精度が失われるのため、Round(Double, Int32, MidpointRounding)メソッドが指定された中間値を丸めるされない可能性がありますによって、modeパラメーター。 Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter. これは 2.135 が 2.14 ではなく 2.13 に丸められますの次の例に示します。 This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. これは、メソッドを内部的に乗算するために発生value10、し、乗算操作は、ここでは精度の損失から低下します。 This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision. [! コード csharpSystem.Math.Round#3] [! コード vbSystem.Math.Round#3] [!code-csharpSystem.Math.Round#3] [!code-vbSystem.Math.Round#3]

See Also

Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding) Round(Double, MidpointRounding)

倍精度浮動小数点値を最も近い整数に丸めます。 Rounds a double-precision floating-point value to the nearest integer. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

public:
 static double Round(double value, MidpointRounding mode);
public static double Round (double value, MidpointRounding mode);
static member Round : double * MidpointRounding -> double
Public Shared Function Round (value As Double, mode As MidpointRounding) As Double

パラメーター

value
Double Double Double Double

丸め対象の倍精度浮動小数点数。 A double-precision floating-point number to be rounded.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

value が 2 つの数値の中間にある場合に丸める方法を指定します。 Specification for how to round value if it is midway between two other numbers.

Returns

value に最も近い整数。 The integer nearest value. value が 2 つの整数 (一方が偶数でもう一方が奇数) の中間にある場合、mode によって 2 つの数値のどちらが返されるかが決まります。 If value is halfway between two integers, one of which is even and the other odd, then mode determines which of the two is returned.

Exceptions

mode が有効な MidpointRounding 値ではありません。 mode is not a valid value of MidpointRounding.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

Notes to Callers

結果を浮動小数点数としての 10 進数の値を表すまたは場合によっては、浮動小数点値に対する算術演算を実行する精度が失われるのため、Round(Double, MidpointRounding)メソッドが、中間の値を丸めるされない可能性があります、近い偶数の整数。 Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, MidpointRounding) method may not appear to round midpoint values to the nearest even integer. 次の例では、浮動小数点値.1 は有限のバイナリ表現があるないため、最初の呼び出し、 Round(Double) 11.5 の値を持つメソッドには、12 の代わりに 11 が返されます。 In the following example, because the floating-point value .1 has no finite binary representation, the first call to the Round(Double) method with a value of 11.5 returns 11 instead of 12. [! コード csharpSystem.Math.Round#4] [! コード vbSystem.Math.Round#4] [!code-csharpSystem.Math.Round#4] [!code-vbSystem.Math.Round#4]

See Also

Round(Double, Int32) Round(Double, Int32) Round(Double, Int32) Round(Double, Int32)

倍精度浮動小数点値を指定した小数部の桁数に丸めます。 Rounds a double-precision floating-point value to a specified number of fractional digits.

public:
 static double Round(double value, int digits);
public static double Round (double value, int digits);
static member Round : double * int -> double
Public Shared Function Round (value As Double, digits As Integer) As Double

パラメーター

value
Double Double Double Double

丸め対象の倍精度浮動小数点数。 A double-precision floating-point number to be rounded.

digits
Int32 Int32 Int32 Int32

戻り値の小数部の桁数。 The number of fractional digits in the return value.

Returns

value に等しい小数部の桁数を格納する digits に最も近い数値。 The number nearest to value that contains a number of fractional digits equal to digits.

Exceptions

digits が 0 より小さいか、15 を超えています。 digits is less than 0 or greater than 15.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

Notes to Callers

結果を浮動小数点数としての 10 進数の値を表すまたは場合によっては、浮動小数点値に対する算術演算を実行する精度が失われるのため、Round(Double, Int32)メソッドが、中間の値を丸めるされない可能性があります、最も近い偶数値で、digits小数部の位置。 Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32) method may not appear to round midpoint values to the nearest even value in the digits decimal position. これは 2.135 が 2.14 ではなく 2.13 に丸められますの次の例に示します。 This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. これは、メソッドを内部的に乗算するために発生value10、し、乗算操作は、ここでは精度の損失から低下します。 This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision. [! コード csharpSystem.Math.Round#2] [! コード vbSystem.Math.Round#2] [!code-csharpSystem.Math.Round#2] [!code-vbSystem.Math.Round#2]

See Also

Round(Double) Round(Double) Round(Double) Round(Double)

倍精度浮動小数点値を最も近い整数値に丸めます。 Rounds a double-precision floating-point value to the nearest integral value.

public:
 static double Round(double a);
public static double Round (double a);
static member Round : double -> double
Public Shared Function Round (a As Double) As Double

パラメーター

a
Double Double Double Double

丸め対象の倍精度浮動小数点数。 A double-precision floating-point number to be rounded.

Returns

a に最も近い整数。 The integer nearest a. a の小数部が 2 つの整数 (一方が偶数で、もう一方が奇数) の中間にある場合は、偶数が返されます。 If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned. このメソッドは、整数型ではなく Double を返します。 Note that this method returns a Double instead of an integral type.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

Notes to Callers

結果を浮動小数点数としての 10 進数の値を表すまたは場合によっては、浮動小数点値に対する算術演算を実行する精度が失われるのため、Round(Double)メソッドが、中間の値を丸めるされない可能性があります、近い偶数の整数。 Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double) method may not appear to round midpoint values to the nearest even integer. 次の例では、浮動小数点値.1 は有限のバイナリ表現があるないため、最初の呼び出し、 Round(Double) 11.5 の値を持つメソッドには、12 の代わりに 11 が返されます。 In the following example, because the floating-point value .1 has no finite binary representation, the first call to the Round(Double) method with a value of 11.5 returns 11 instead of 12. [! コード csharpSystem.Math.Round#1] [! コード vbSystem.Math.Round#1] [!code-csharpSystem.Math.Round#1] [!code-vbSystem.Math.Round#1]

See Also

Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32) Round(Decimal, Int32)

10 進値を、指定した小数部の桁数に丸めます。 Rounds a decimal value to a specified number of fractional digits.

public:
 static System::Decimal Round(System::Decimal d, int decimals);
public static decimal Round (decimal d, int decimals);
static member Round : decimal * int -> decimal
Public Shared Function Round (d As Decimal, decimals As Integer) As Decimal

パラメーター

d
Decimal Decimal Decimal Decimal

丸め対象の 10 進数。 A decimal number to be rounded.

decimals
Int32 Int32 Int32 Int32

戻り値の小数部の桁数。 The number of decimal places in the return value.

Returns

d に等しい小数部の桁数を格納する decimals に最も近い数値。 The number nearest to d that contains a number of fractional digits equal to decimals.

Exceptions

decimals が 0 未満か、28 を超えています。 decimals is less than 0 or greater than 28.

結果が Decimal の範囲外です。 The result is outside the range of a Decimal.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

See Also

Round(Decimal) Round(Decimal) Round(Decimal) Round(Decimal)

10 進値を最も近い整数値に丸めます。 Rounds a decimal value to the nearest integral value.

public:
 static System::Decimal Round(System::Decimal d);
public static decimal Round (decimal d);
static member Round : decimal -> decimal
Public Shared Function Round (d As Decimal) As Decimal

パラメーター

d
Decimal Decimal Decimal Decimal

丸め対象の 10 進数。 A decimal number to be rounded.

Returns

パラメーター d に最も近い整数。 The integer nearest parameter d. d の小数部が 2 つの整数 (一方が偶数で、もう一方が奇数) の中間にある場合は、偶数が返されます。 If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. このメソッドは、整数型ではなく Decimal を返します。 Note that this method returns a Decimal instead of an integral type.

Exceptions

結果が Decimal の範囲外です。 The result is outside the range of a Decimal.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

See Also

Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding) Round(Decimal, MidpointRounding)

10 進値を最も近い整数に丸めます。 Rounds a decimal value to the nearest integer. 値が 2 つの数値の中間にある場合にその値を丸める方法をパラメーターで指定します。 A parameter specifies how to round the value if it is midway between two numbers.

public:
 static System::Decimal Round(System::Decimal d, MidpointRounding mode);
public static decimal Round (decimal d, MidpointRounding mode);
static member Round : decimal * MidpointRounding -> decimal
Public Shared Function Round (d As Decimal, mode As MidpointRounding) As Decimal

パラメーター

d
Decimal Decimal Decimal Decimal

丸め対象の 10 進数。 A decimal number to be rounded.

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

d が 2 つの数値の中間にある場合に丸める方法を指定します。 Specification for how to round d if it is midway between two other numbers.

Returns

d に最も近い整数。 The integer nearest d. d が 2 つの数値 (一方が偶数でもう一方が奇数) の中間にある場合、mode によって 2 つの数値のどちらが返されるかが決まります。 If d is halfway between two numbers, one of which is even and the other odd, then mode determines which of the two is returned.

Exceptions

mode が有効な MidpointRounding 値ではありません。 mode is not a valid value of MidpointRounding.

結果が Decimal の範囲外です。 The result is outside the range of a Decimal.

Remarks

注意

例との他のオーバー ロードの包括的な使用状況について、Roundメソッドを参照してください、Roundリファレンス ページです。For examples and comprehensive usage information about this and other overloads of the Round method, see the Round reference page.

See Also

Applies to