108

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?

Scott
  • 4,066
  • 10
  • 38
  • 54

3 Answers3

190

Use Math.Ceiling()

double result = Math.Ceiling(1.02);
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
30

Use Math.Ceiling: Math.Ceiling(value)

Talljoe
  • 14,593
  • 4
  • 43
  • 39
13

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)
SunsetQuest
  • 8,041
  • 2
  • 47
  • 42
  • 1
    Math.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! – eKKiM Apr 18 '22 at 09:45