How to round up in c#
122,877
Solution 1
Use Math.Ceiling()
double result = Math.Ceiling(1.02);
Solution 2
Use Math.Ceiling:
Math.Ceiling(value)
Solution 3
If negative values are present, Math.Round has additional options (in .Net Core 3 or later).
I did a benchmark(.Net 5/release) though and Math.Ceiling() is faster and more efficient.
Math.Round( 6.88, MidpointRounding.ToPositiveInfinity) ==> 7 (~23 clock cycles)
Math.Round(-6.88, MidpointRounding.ToPositiveInfinity) ==> -6 (~23 clock cycles)
Math.Round( 6.88, MidpointRounding.AwayFromZero) ==> 7 (~23 clock cycles)
Math.Round(-6.88, MidpointRounding.AwayFromZero) ==> -7 (~23 clock cycles)
Math.Ceiling( 6.88) ==> 7 (~1 clock cycles)
Math.Ceiling(-6.88) ==> -6 (~1 clock cycles)
Related videos on Youtube
Author by
Scott
Updated on December 27, 2020Comments
-
Scott over 3 years
I want to round up always in c#, so for example, from 6.88 to 7, from 1.02 to 2, etc.
How can I do that?
-
Talljoe about 13 yearspossible duplicate of how to always round up to the next integer
-
Felice Pollano about 13 yearsTry to write Math. and look with enough attention to all the function you see
-
Henk Holterman about 13 yearsIncomplete specs. What should -1.02 become?
-
Bek Raupov about 13 yearssimple googling would have helped :)
-
Todd Painton about 9 yearsyep, I googled, first on the list was this post... Thanks for asking.
-
-
Scott about 13 yearsFirst one I saw. This is more clear than using awayfromzero. Thanks!
-
cHao about 13 yearsClearer, and correct. :)
AwayFromZero
is used for something else, and would break for you in this case. -
Kyle Delaney almost 7 yearsIs there an option that returns an
int
orlong
instead? -
henry.dv over 5 years@KyleDelaney no, but you can easily cast it via
(int) Math.Ceiling(someDouble);
. -
Kyle Delaney over 5 years@henry.dv - I wonder why a rounding function would return a double to begin with
-
RedGreenCode over 4 years@KyleDelaney stackoverflow.com/questions/5693468/…
-
eKKiM about 2 yearsMath.Round has the advantage that it has the possibility to round to a given amount of decimals. While this is not possible with Math.Ceiling!