76

In C#, how do I round a float upwards to the nearest int?

I see Math.Ceiling and Math.Round, but these returns a decimal. Do I use one of these then cast to an Int?

Fattie
  • 27,874
  • 70
  • 431
  • 719
  • See http://stackoverflow.com/questions/14/whats-the-difference-between-math-floor-and-math-truncate-in-net for a full roundup. – paxdiablo May 25 '09 at 02:44

6 Answers6

162

If you want to round to the nearest int:

int rounded = (int)Math.Round(precise, 0);

You can also use:

int rounded = Convert.ToInt32(precise);

Which will use Math.Round(x, 0); to round and cast for you. It looks neater but is slightly less clear IMO.


If you want to round up:

int roundedUp = (int)Math.Ceiling(precise);
mmcdole
  • 91,488
  • 60
  • 186
  • 222
Matt Brindley
  • 9,739
  • 7
  • 47
  • 51
  • 9
    There is ambiguity in the question. The title suggests he wants to round up, while he states he wants the nearest int. These are 2 different things. – mmcdole May 25 '09 at 01:01
  • He wanted to round up. Wouldn't that be (int)Math.Ceiling(precise) ? – configurator May 25 '09 at 01:01
  • @configurator, yea, that is what I'm thinking. – mmcdole May 25 '09 at 01:04
  • 17
    I'd also like to note that Math.Round uses banker's rounding. That is, a number with a non-integer part of exactly .5 would be rounded to the nearest even number. This is useful when doing aggregate sums of rounded numbers, but is usually unexpected - Math.Round(3.5) = 4, Math.Round(6.5) = 6. – configurator May 27 '09 at 18:04
  • Isn't there a risk of floating-point inaccuracies causing trouble here? If `Math.Round(precise, 0)` yields a floating-point value which is smaller than the actual value by any non-zero amount, `(int)Math.Round(precise, 0)` would equal `(int)precise`, right? I imagine a simpler and safer solution would be to simply use `int rounded = (int)(precise+.5f);`. – krainert Aug 01 '15 at 09:06
  • Round takes double arguments. The poster asked for float. – jeancallisti Mar 04 '19 at 12:11
  • @jeancallisti It should go without saying that the float can be cast to a double – arkon Sep 15 '19 at 12:01
18

Off the top of my head:

float fl = 0.678;
int rounded_f = (int)(fl+0.5f);
Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46
3

(int)Math.Round(myNumber, 0)

joshcomley
  • 28,099
  • 24
  • 107
  • 147
3

The easiest is to just add 0.5f to it and then cast this to an int.

JulianR
  • 16,213
  • 5
  • 55
  • 85
1

Do I use one of these then cast to an Int?

Yes. There is no problem doing that. Decimals and doubles can represent integers exactly, so there will be no representation error. (You won't get a case, for instance, where Round returns 4.999... instead of 5.)

dan-gph
  • 16,301
  • 12
  • 61
  • 79
0

You can cast to an int provided you are sure it's in the range for an int (Int32.MinValue to Int32.MaxValue).

Joe
  • 122,218
  • 32
  • 205
  • 338