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

定義

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

オーバーロード

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

10 進数の値は指定した小数部の桁数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a decimal value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

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

倍精度浮動小数点の値は指定した小数部の桁数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a double-precision floating-point value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

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

倍精度浮動小数点の値は最も近い整数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a double-precision floating-point value to the nearest integer, and uses the specified rounding convention for midpoint values.

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

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

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

倍精度浮動小数点の値は最も近い整数値に丸められ、中間値は最も近い偶数値に丸められます。Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.

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

10 進数の値は指定した小数部の桁数に丸められ、中間値は最も近い偶数値に丸められます。Rounds a decimal value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

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

10 進数の値は最も近い整数値に丸められ、中間値は最も近い偶数値に丸められます。Rounds a decimal value to the nearest integral value, and rounds midpoint values to the nearest even number.

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

10 進数の値は最も近い整数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a decimal value to the nearest integer, and uses the specified rounding convention for midpoint values.

この記事には、 「解説」の例に加えて、 Math.Roundメソッドの次のオーバーロードを示す例が含まれています。In addition to the examples in the Remarks section, this article includes examples that illustrate the following overloads of the Math.Round method:

Math. Round (Decimal)Math.Round(Decimal)
Math. Round (Double)Math.Round(Double)
Math. Round (Decimal, Int32)Math.Round(Decimal, Int32)
Math. Round (Decimal, Midpointrounding.awayfromzero)Math.Round(Decimal, MidpointRounding)
Math. Round (Double, Int32)Math.Round(Double, Int32)
Math. Round (Double, Midpointrounding.awayfromzero)Math.Round(Double, MidpointRounding)
Math. Round (Decimal, Int32, Midpointrounding.awayfromzero)Math.Round(Decimal, Int32, MidpointRounding)
Math. Round (Double, Int32, Midpointrounding.awayfromzero)Math.Round(Double, Int32, MidpointRounding)

注意

この記事の C# 例は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。The C# examples in this article run in the Try.NET inline code runner and playground. [実行] ボタンを選択すると、対話型ウィンドウで例が実行されます。Select the Run button to run an example in an interactive window. コードを実行したら、コードを変更し、 [実行] をもう一度選択して変更後のコードを実行できます。Once you execute the code, you can modify it and run the modified code by selecting Run again. 変更後のコードが対話型ウィンドウで実行されるか、コンパイルできなかった場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

注釈

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

どの方法を呼び出すか。Which method do I call?

次の表を使用して、適切な丸め方法を選択できます。You can use the following table to select an appropriate rounding method. Math.Roundメソッドに加えて、およびMath.Floorも含まれMath.Ceilingます。In addition to the Math.Round methods, it also includes Math.Ceiling and Math.Floor.

終了To CallCall
近似値への丸め規則を使用して、数値を整数に丸めます。Round a number to an integer by using the rounding to nearest convention. Round(Decimal)

または-or-

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

または-or-

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

または-or-

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

- または --or-

Round(Double, Int32, MidpointRounding)
指定さSingleれた丸め規則を使用し、精度の低下を最小限に抑えるために、指定した小数部の桁数に値を丸めます。Round a Single value to a specified number of fractional digits by using a specified rounding convention and minimizing the loss of precision. SingleRound(Decimal, Int32, MidpointRounding)に変換し、を呼び出します。DecimalConvert 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.85 は3.9 に、-3.75 は-3.8、-3.85 は-3.9 に丸められます。For example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8, and -3.85 rounds to -3.9. この形式の丸めは、 MidpointRounding.AwayFromZero列挙体のメンバーによって表されます。This form of rounding is represented by the MidpointRounding.AwayFromZero enumeration member.

    0からの丸め処理は、最も広く知られている丸め形式です。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 Standard 754 のセクション4に準拠しています。It conforms to IEEE Standard 754, section 4. 複数の丸め処理で使用すると、一貫して中間値を一方向に丸めることによって発生する丸め誤差を減らすことができます。When used in multiple rounding operations, it reduces the rounding error that is caused by consistently rounding midpoint values in a single direction. 場合によっては、この丸め誤差が重要になることがあります。In some cases, this rounding error can be significant.

    次の例は、中間値を常に一方向に丸めることによって生じる可能性があるバイアスを示しています。The following example illustrates the bias that can result from consistently rounding midpoint values in a single direction. この例では、値のDecimal配列の真の平均を計算し、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. ただし、0から丸めたときの結果の平均は、0.05 (または 3.6%) によって異なります。真の平均からです。However, the mean that results when rounding away from zero differs by .05 (or by 3.6%) from the true mean.

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

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

オーバーロードOverload 丸め規則Rounding convention
Round(Decimal) ToEven
Round(Double) ToEven
Round(Decimal, Int32) ToEven
Round(Double, Int32) ToEven
Round(Decimal, MidpointRounding) パラメーターにmodeよって決定されます。Determined by mode parameter.
Round(Double, MidpointRounding) パラメーターにmodeよって決定Determined by mode parameter
Round(Decimal, Int32, MidpointRounding) パラメーターにmodeよって決定Determined by mode parameter
Round(Double, Int32, MidpointRounding) パラメーターにmodeよって決定Determined by mode parameter

丸めと精度Rounding and precision

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

重要

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

この問題の例を次に示します。The following example illustrates the problem. 繰り返し、0.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. この例に示すように、 Double変数に定数値11.5 を代入するだけでは、この問題は発生しません。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には、型およびDoubleDecimalの引数を受け入れるオーバーロードが含まれています。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 C# Double Round Doubleメソッドのいずれかのオーバーロードに値を渡すと、キャスト (では) または変換 (Visual Basic) がになり、パラメーターを持つ対応するオーバーロードが呼び出されます。 RoundIf 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. 値16.325 がRoundメソッドに渡され、近似値への丸め処理を使用して小数点以下2桁に丸められた場合、結果は16.33 で、予期された16.32 の結果ではありません。 SingleWhen 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. 16.325000762939453 の結果Doubleの値は中間値ではなく、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.

多くの場合、例に示すように、 SingleDecimalをにキャストまたは変換することによって、精度の低下を最小限に抑えることができます。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.

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, and uses the specified rounding convention for midpoint values.

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

パラメーター

d
Decimal Decimal Decimal Decimal

丸め対象の 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.

戻り値

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.

例外

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

modeMidpointRounding の正しい値ではありません。mode is not a valid value of MidpointRounding.

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

注釈

中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

decimals引数の値は、0から28までの範囲で指定できます。The value of the decimals argument can range from 0 to 28.

Example

次の例は、 RoundメソッドをMidpointRounding列挙体と共に使用する方法を示しています。The following example demonstrates how to use the Round method with the MidpointRounding enumeration.

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

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

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

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

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

/*
This code example produces the following results:

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

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

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

*/
decimal result = 0.0m;
decimal posValue =  3.45m;
decimal negValue = -3.45m;

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

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

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

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

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

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

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

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

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

*/
' This example demonstrates the Math.Round() method in conjunction 
' with the MidpointRounding enumeration.
Class Sample
    Public Shared Sub Main() 
        Dim result As Decimal = 0D
        Dim posValue As Decimal = 3.45D
        Dim negValue As Decimal = -3.45D
        
        ' By default, round a positive and a negative value to the nearest even number. 
        ' The precision of the result is 1 decimal place.
        result = Math.Round(posValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue)
        result = Math.Round(negValue, 1)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue)
        Console.WriteLine()
        
        ' Round a positive value to the nearest even number, then to the nearest number 
        ' away from zero. The precision of the result is 1 decimal place.
        result = Math.Round(posValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", _
                           result, posValue)
        result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", _
                           result, posValue)
        Console.WriteLine()
        
        ' Round a negative value to the nearest even number, then to the nearest number 
        ' away from zero. The precision of the result is 1 decimal place.
        result = Math.Round(negValue, 1, MidpointRounding.ToEven)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", _
                            result, negValue)
        result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
        Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", _
                           result, negValue)
        Console.WriteLine()
    
    End Sub 'Main
End Class 'Sample
'
'This code example produces the following results:
'
' 3.4 = Math.Round( 3.45, 1)
'-3.4 = Math.Round(-3.45, 1)
'
' 3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
' 3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)
'
'-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
'-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
'
こちらもご覧ください

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

倍精度浮動小数点の値は指定した小数部の桁数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a double-precision floating-point value to a specified number of fractional digits, and uses the specified rounding convention for midpoint values.

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

パラメーター

value
Double Double Double Double

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

digits
Int32 Int32 Int32 Int32

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

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

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

戻り値

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.

例外

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

modeMidpointRounding の正しい値ではありません。mode is not a valid value of MidpointRounding.

注釈

digits引数の値は 0 ~ 15 の範囲で指定できます。The value of the digits argument can range from 0 to 15. 15は、 Double型でサポートされる整数および小数部の最大数であることに注意してください。Note that 15 is the maximum number of integral and fractional digits supported by the Double type.

中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

value引数の値がDouble.NaNの場合、メソッドはを返しDouble.NaNます。If the value of the value argument is Double.NaN, the method returns Double.NaN. value またDouble.PositiveInfinity Double.PositiveInfinity Double.NegativeInfinityはの場合、メソッドはそれぞれまたはを返します。 Double.NegativeInfinityIf value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

Example

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

 double posValue =  3.45;
 double negValue = -3.45;

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

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

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

注意 (呼び出し元)

Decimal 型の値を浮動小数点数として表現したり、浮動小数点値に対して算術演算を実行したりすることによっ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. これは、メソッドの内部でvalue 10が乗算され、この場合の乗算演算で精度が低下しているために発生します。This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

[!code-csharpSystem.Math.Round#3] [!code-vbSystem.Math.Round#3][!code-csharpSystem.Math.Round#3] [!code-vbSystem.Math.Round#3]

こちらもご覧ください

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

倍精度浮動小数点の値は最も近い整数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a double-precision floating-point value to the nearest integer, and uses the specified rounding convention for midpoint values.

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

パラメーター

value
Double Double Double Double

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

mode
MidpointRounding MidpointRounding MidpointRounding MidpointRounding

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

戻り値

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. このメソッドは、整数型ではなく Double を返します。Note that this method returns a Double instead of an integral type.

例外

modeMidpointRounding の正しい値ではありません。mode is not a valid value of MidpointRounding.

注釈

中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

value引数の値がDouble.NaNの場合、メソッドはを返しDouble.NaNます。If the value of the value argument is Double.NaN, the method returns Double.NaN. value またDouble.PositiveInfinity Double.PositiveInfinity Double.NegativeInfinityはの場合、メソッドはそれぞれまたはを返します。 Double.NegativeInfinityIf value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

Example

次の例でRound(Double)は、メソッドによって返される値Round(Double, MidpointRounding)modeToEven引数を持つメソッドRound(Double, MidpointRounding) 、および引数mode AwayFromZeroを持つメソッドを表示します。The 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

注意 (呼び出し元)

Decimal 型の値を浮動小数点数として表現したり、浮動小数点値に対して算術演算を実行したりすることによっ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 に有限のバイナリ表現がないため、11.5 の値Round(Double)を持つメソッドの最初の呼び出しでは、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.

[!code-csharpSystem.Math.Round#4] [!code-vbSystem.Math.Round#4][!code-csharpSystem.Math.Round#4] [!code-vbSystem.Math.Round#4]

こちらもご覧ください

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

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

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

パラメーター

value
Double Double Double Double

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

digits
Int32 Int32 Int32 Int32

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

戻り値

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

例外

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

注釈

digits引数の値は 0 ~ 15 の範囲で指定できます。The value of the digits argument can range from 0 to 15. 15は、 Double型でサポートされる整数および小数部の最大数であることに注意してください。Note that 15 is the maximum number of integral and fractional digits supported by the Double type.

このメソッドは、の既定のMidpointRounding.ToEven丸め規則を使用します。This method uses the default rounding convention of MidpointRounding.ToEven. 中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

value引数の値がDouble.NaNの場合、メソッドはを返しDouble.NaNます。If the value of the value argument is Double.NaN, the method returns Double.NaN. value またDouble.PositiveInfinity Double.PositiveInfinity Double.NegativeInfinityはの場合、メソッドはそれぞれまたはを返します。 Double.NegativeInfinityIf value is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

Example

次の例では、2桁の小数部を含む double 型の値を、1桁の小数部を持つ倍精度浮動小数点数で丸めます。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

注意 (呼び出し元)

Decimal 型の値を浮動小数点数として表現したり、浮動小数点値に対して算術演算を実行したりすることによっ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. これは、メソッドの内部でvalue 10が乗算され、この場合の乗算演算で精度が低下しているために発生します。This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

[!code-csharpSystem.Math.Round#2] [!code-vbSystem.Math.Round#2][!code-csharpSystem.Math.Round#2] [!code-vbSystem.Math.Round#2]

こちらもご覧ください

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

倍精度浮動小数点の値は最も近い整数値に丸められ、中間値は最も近い偶数値に丸められます。Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.

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

パラメーター

a
Double Double Double Double

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

戻り値

a に最も近い整数。The integer nearest a. a の小数部が 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.

注釈

このメソッドは、の既定のMidpointRounding.ToEven丸め規則を使用します。This method uses the default rounding convention of MidpointRounding.ToEven. 中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

a引数の値がDouble.NaNの場合、メソッドはを返しDouble.NaNます。If the value of the a argument is Double.NaN, the method returns Double.NaN. a またDouble.PositiveInfinity Double.PositiveInfinity Double.NegativeInfinityはの場合、メソッドはそれぞれまたはを返します。 Double.NegativeInfinityIf a is Double.PositiveInfinity or Double.NegativeInfinity, the method returns Double.PositiveInfinity or Double.NegativeInfinity, respectively.

Visual Basic 15.8 以降では、 Roundメソッドによって返された値を任意の整数変換関数に渡した場合、またはによってRound返された double 値がの場合に、倍精度整数変換のパフォーマンスが最適化されます。は、 Option Strictが Off に設定されている整数に自動的に変換されます。Starting with Visual Basic 15.8, the performance of Double-to-integer conversion is optimized if you pass the value returned by the Round method to the any of the integral conversion functions, or if the Double value returned by Round is automatically converted to an integer with Option Strict set to Off. この最適化によって、コードをより速く実行できます。大きい数値の整数型への変換を行うコードでは、最大で 2 倍速くなります。This optimization allows code to run faster -- up to twice as fast for code that does a large number of conversions to integer types. 次の例は、このような最適化された変換を示しています。The following example illustrates such optimized conversions:

Dim d1 As Double = 1043.75133
Dim i1 As Integer = CInt(Math.Ceiling(d1))        ' Result: 1044

Dim d2 As Double = 7968.4136
Dim i2 As Integer = CInt(Math.Ceiling(d2))        ' Result: 7968

Example

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

using namespace System;

void main()
{
    Console::WriteLine("Classic Math.Round in CPP");
    Console::WriteLine(Math::Round(4.4));     // 4
    Console::WriteLine(Math::Round(4.5));     // 4
    Console::WriteLine(Math::Round(4.6));     // 5
    Console::WriteLine(Math::Round(5.5));     // 6
}
Console.WriteLine("Classic Math.Round in CSharp");
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
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

注意 (呼び出し元)

Decimal 型の値を浮動小数点数として表現したり、浮動小数点値に対して算術演算を実行したりすることによっ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 に有限のバイナリ表現がないため、11.5 の値Round(Double)を持つメソッドの最初の呼び出しでは、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.

[!code-csharpSystem.Math.Round#1] [!code-vbSystem.Math.Round#1][!code-csharpSystem.Math.Round#1] [!code-vbSystem.Math.Round#1]

こちらもご覧ください

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

10 進数の値は指定した小数部の桁数に丸められ、中間値は最も近い偶数値に丸められます。Rounds a decimal value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

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

パラメーター

d
Decimal Decimal Decimal Decimal

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

decimals
Int32 Int32 Int32 Int32

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

戻り値

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

例外

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

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

注釈

decimals引数の値は、0から28までの範囲で指定できます。The value of the decimals argument can range from 0 to 28.

このメソッドは、の既定のMidpointRounding.ToEven丸め規則を使用します。This method uses the default rounding convention of MidpointRounding.ToEven. 中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

Example

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

Console.WriteLine(Math.Round(3.44m, 1)); 
Console.WriteLine(Math.Round(3.45m, 1)); 
Console.WriteLine(Math.Round(3.46m, 1)); 
Console.WriteLine();

Console.WriteLine(Math.Round(4.34m, 1)); 
Console.WriteLine(Math.Round(4.35m, 1)); 
Console.WriteLine(Math.Round(4.36m, 1)); 
// The example displays the following output:
//       3.4
//       3.4
//       3.5
//       
//       4.3
//       4.4
//       4.4
Public Module Example
   Sub Main()
      Console.WriteLine(Math.Round(3.44, 1)) 
      Console.WriteLine(Math.Round(3.45, 1)) 
      Console.WriteLine(Math.Round(3.46, 1)) 
      Console.WriteLine()
      
      Console.WriteLine(Math.Round(4.34, 1)) 
      Console.WriteLine(Math.Round(4.35, 1)) 
      Console.WriteLine(Math.Round(4.36, 1)) 
   End Sub  
End Module
' The example displays the following output:
'       3.4
'       3.4
'       3.5
'       
'       4.3
'       4.4
'       4.4
こちらもご覧ください

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

10 進数の値は最も近い整数値に丸められ、中間値は最も近い偶数値に丸められます。Rounds a decimal value to the nearest integral value, and rounds midpoint values to the nearest even number.

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

パラメーター

d
Decimal Decimal Decimal Decimal

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

戻り値

d パラメーターに最も近い整数。The integer nearest the d parameter. 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.

例外

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

注釈

このメソッドは、の既定のMidpointRounding.ToEven丸め規則を使用します。This method uses the default rounding convention of MidpointRounding.ToEven. 中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

Example

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

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

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

10 進数の値は最も近い整数に丸められ、中間値には指定した丸め処理が使用されます。Rounds a decimal value to the nearest integer, and uses the specified rounding convention for midpoint values.

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

パラメーター

d
Decimal Decimal Decimal Decimal

丸め対象の 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.

戻り値

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. このメソッドは、整数型ではなく Decimal を返します。Note that this method returns a Decimal instead of an integral type.

例外

modeMidpointRounding の正しい値ではありません。mode is not a valid value of MidpointRounding.

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

注釈

中間値を使用した数値の丸め処理の詳細については、「中間値と丸め規則」を参照してください。See Midpoint values and rounding conventions for information about rounding numbers with midpoint values.

重要

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

Example

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

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

適用対象