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)
Share:
122,877

Related videos on Youtube

Scott
Author by

Scott

Updated on December 27, 2020

Comments

  • Scott
    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
      Talljoe about 13 years
    • Felice Pollano
      Felice Pollano about 13 years
      Try to write Math. and look with enough attention to all the function you see
    • Henk Holterman
      Henk Holterman about 13 years
      Incomplete specs. What should -1.02 become?
    • Bek Raupov
      Bek Raupov about 13 years
      simple googling would have helped :)
    • Todd Painton
      Todd Painton about 9 years
      yep, I googled, first on the list was this post... Thanks for asking.
  • Scott
    Scott about 13 years
    First one I saw. This is more clear than using awayfromzero. Thanks!
  • cHao
    cHao about 13 years
    Clearer, and correct. :) AwayFromZero is used for something else, and would break for you in this case.
  • Kyle Delaney
    Kyle Delaney almost 7 years
    Is there an option that returns an int or long instead?
  • henry.dv
    henry.dv over 5 years
    @KyleDelaney no, but you can easily cast it via (int) Math.Ceiling(someDouble);.
  • Kyle Delaney
    Kyle Delaney over 5 years
    @henry.dv - I wonder why a rounding function would return a double to begin with
  • RedGreenCode
    RedGreenCode over 4 years
  • eKKiM
    eKKiM about 2 years
    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!