Reputation: 4334
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!
Upvotes: 36
Views: 78331
Reputation: 30208
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
Upvotes: 16
Reputation: 376
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")
Upvotes: 0
Reputation: 101
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
Upvotes: 2
Reputation: 4259
The number is fine for double
type of variable, and mathematically correct.
You have two well establish solutions to avoid the such situations.
Math
library.I you want to know why you see this "weird" number, you can read there : irrational numbers
Upvotes: 5
Reputation: 1807
double test2 = 87.2345524523452;
double test3 = Math.Round(test2, 2);
Upvotes: 6
Reputation: 3665
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.
Upvotes: 97
Reputation: 24232
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.
Upvotes: 42