How to round up in c#

C#Rounding

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Use Math.Ceiling()

double result = Math.Ceiling(1.02);

Solution 2 - C#

Use Math.Ceiling: Math.Ceiling(value)

Solution 3 - C#

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionScottView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#TalljoeView Answer on Stackoverflow
Solution 3 - C#SunsetQuestView Answer on Stackoverflow