LoginSignup
32
23

More than 5 years have passed since last update.

[C#] Math.Round 関数は単純な四捨五入ではない

Posted at

Math.Round メソッドで四捨五入対象桁が 5 の場合
必ずしも繰り上げにならないことがある。

Debug.WriteLine(string.Format("Math.Round(0.15, 1)\t{0}", Math.Round(0.15, 1)));
Debug.WriteLine(string.Format("Math.Round(0.25, 1)\t{0}", Math.Round(0.25, 1)));
Debug.WriteLine(string.Format("Math.Round(0.35, 1)\t{0}", Math.Round(0.35, 1)));
Debug.WriteLine(string.Format("Math.Round(0.45, 1)\t{0}", Math.Round(0.45, 1)));

実行結果は以下の通りになります。

Math.Round(0.15, 1) 0.2
Math.Round(0.25, 1) 0.2
Math.Round(0.35, 1) 0.4
Math.Round(0.45, 1) 0.4

四捨五入桁の手前の数字が偶数になるように丸められるようです。
以下のリンクで詳しく説明がされています。

小数点を切り捨て、切り上げ、四捨五入する

一般的な四捨五入にしたい場合は、MidpointRounding.AwayFromZero を指定します。

Debug.WriteLine(string.Format("Math.Round(0.15, 1, MidpointRounding.AwayFromZero)\t{0}", Math.Round(0.15, 1, MidpointRounding.AwayFromZero)));
Debug.WriteLine(string.Format("Math.Round(0.25, 1, MidpointRounding.AwayFromZero)\t{0}", Math.Round(0.25, 1, MidpointRounding.AwayFromZero)));
Debug.WriteLine(string.Format("Math.Round(0.35, 1, MidpointRounding.AwayFromZero)\t{0}", Math.Round(0.35, 1, MidpointRounding.AwayFromZero)));
Debug.WriteLine(string.Format("Math.Round(0.45, 1, MidpointRounding.AwayFromZero)\t{0}", Math.Round(0.45, 1, MidpointRounding.AwayFromZero)));

実行結果は以下のように四捨五入されます。

Math.Round(0.15, 1, MidpointRounding.AwayFromZero)  0.2
Math.Round(0.25, 1, MidpointRounding.AwayFromZero)  0.3
Math.Round(0.35, 1, MidpointRounding.AwayFromZero)  0.4
Math.Round(0.45, 1, MidpointRounding.AwayFromZero)  0.5
32
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
23