Rounding values up or down in C#

醉酒当歌 提交于 2019-11-29 13:07:05

Try using Math.Round. Its various overloads allow you to specify how many digits you want and also which way you want it to round the number.

Use Math.Ceiling(87.124563563566) or Math.Floor(87.124563563566) for always rounding up or rounding down. I believe this goes to the nearest whole number.

To always round down to 2 decimal places:

decimal score = 87.126;
Math.Floor(score * 100) / 100; // 87.12

To always round up to 2 decimal places:

decimal score = 87.124;
Math.Ceiling(score * 100) / 100; // 87.13

You just want to format the string, not to corrupt the score.

double test2 = 87.2345524523452;
double test3 = Math.Round(test2, 2);

The number is fine for double type of variable, and mathematically correct.
You have two well establish solutions to avoid the such situations.

  1. string solution : When you show the number to users, just do it : variable.ToString("0.00"). The ToString is just cutting the number.
  2. rounding solution : If you want to control the rounding ,you can use the Math library.

I you want to know why you see this "weird" number, you can read there : irrational numbers

I do not have enough reputation to add comments, so I have to create an answer. But timurid is right, just format the string.

I think the thing you are looking for is:

var myScore = 87.124563563566
var toShowOnScreen = myScore.ToString("0.00");

Some of the custom ways to format your values are described here: https://msdn.microsoft.com/en-US/library/7x5bacwt(v=vs.80).aspx

A lot of people are advocating you use the Math library to Round your number, but even that can result in very minor rounding errors. Math.Round can, and sometimes does return numbers with a number of trailing zeros and very small round off errors. This is because, internally, floats and doubles are still represented as binary numbers, and so it can often be hard to represent certain small decimal numbers cleanly.

Your best option is to either only use string formating or, if you do want it to actually round, combine the two:

Math.Round(val, 2).ToString("0.00")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!