Round Up a double to int

54,743

Solution 1

Are you asking about System.Math.Ceiling?

Math.Ceiling(0.2) == 1
Math.Ceiling(0.8) == 1
Math.Ceiling(2.6) == 3
Math.Ceiling(-1.4) == -1

Solution 2

int scaled = (int)Math.Ceiling( (double) 10 / 3 ) ;

Solution 3

By "Approximation by Excess", I assume you're trying to "round up" the number of type double. So, @Doug McClean's "ceiling" method works just fine.

Here is a note: If you start with double x = 0.8; and you do the type conversion by (int)x; you get 0. Or, if you do (int)Math.Round(x); you get 1. If you start with double y = 0.4; and you do the type conversion by (int)y; you get 0. Or, if you do (int)Math.Round(y); you get 0.

Share:
54,743

Related videos on Youtube

markzzz
Author by

markzzz

Updated on July 09, 2022

Comments

  • markzzz
    markzzz almost 2 years

    I have a number ("double") from int/int (such as 10/3).

    What's the best way to Approximation by Excess and convert it to int on C#?

    • An Old Fortran Hacker
      An Old Fortran Hacker over 12 years
      What is 'Approximation by Excess' ?
    • markzzz
      markzzz over 12 years
      Uhm...maybe I don't know how to call it in english? :) Well, if you have 0.2->1; 0.8->1...and so on..."round" to the next int?
    • CodesInChaos
      CodesInChaos over 12 years
      Do you mean (int)Math.Ceiling(x)?
    • markzzz
      markzzz over 12 years
      Oh...it's Round Up! Sorry, thanks :)
    • Jodrell
      Jodrell over 12 years
      Should -1.5 round to -1 or -2?
  • High Performance Mark
    High Performance Mark over 12 years
    Math.Ceiling(-1.4)==-2 -- what language is that ? Tell me it's name so that I can shun it like the plague.
  • Doug McClean
    Doug McClean over 12 years
    Oops, I screwed that up. I looked it up, but I misread the example.
  • Mark Rhodes
    Mark Rhodes about 10 years
    I think you need to cast it for this to work.. i.e. int scaled = (int)Math.Ceiling( (double 10 / 3 );
  • Zegar
    Zegar almost 4 years
    @HighPerformanceMark - well, in C# expression "Math.Ceiling(-1.4)==-2" is correct and basically returns false ;-)
  • ataraxia
    ataraxia almost 4 years
    Seeing how Math.Ceiling returns a decimal and not an int, then no, but OP has accepted this as the answer anyway for some reason.