Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away