简体   繁体   中英

Rounding values up or down in C#

I've created a game which gives a score at the end of the game, but the problem is that this score is sometimes a number with a lot of digits after the decimal point (like 87.124563563566). How would I go about rounding up or down the value so that I could have something like 87.12?

Thanks!

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.

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.

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

您只想格式化字符串,而不破坏分数。

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM