c11ada
c11ada

Reputation: 4334

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!

Upvotes: 36

Views: 78331

Answers (8)

Serj Sagan
Serj Sagan

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

Psymunn
Psymunn

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

Kabwla-TwoLips
Kabwla-TwoLips

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

Avram
Avram

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.

  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

Upvotes: 5

Timurid
Timurid

Reputation: 123

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

Upvotes: 7

Charles Gargent
Charles Gargent

Reputation: 1807

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

Upvotes: 6

Jim
Jim

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

Zach Johnson
Zach Johnson

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

Related Questions