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

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
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