Rounding values up or down in C#
69,982
Solution 1
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.
Solution 2
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.
Solution 3
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
Solution 4
You just want to format the string, not to corrupt the score.
Solution 5
double test2 = 87.2345524523452;
double test3 = Math.Round(test2, 2);
Author by
c11ada
Updated on June 18, 2020Comments
-
c11ada almost 4 years
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!
-
Dirk Vollmar about 14 yearsAnd you most probably want to use
Math.Round(87.123453563566, 2, MidpointRounding.AwayFromZero);
. -
Josue Rocha about 9 yearsThis is just what I was looking for, the functions that do the same as Excel ROUNDUP & ROUNDOWN functions. Thanks a lot!
-
Slagmoth about 6 yearsYou might put an example of that in your answer... I know this is old but it could help.
-
Krish almost 5 yearsI would like to convert/round the following value
string value="12.6"
and need to store it in to an integer... -
Tronald over 4 yearsThis is the best answer!