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