How do I round a float upwards to the nearest int in C#?

后端 未结 6 1068
悲哀的现实
悲哀的现实 2020-12-08 09:43

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?<

相关标签:
6条回答
  • 2020-12-08 09:50

    Off the top of my head:

    float fl = 0.678;
    int rounded_f = (int)(fl+0.5f);
    
    0 讨论(0)
  • 2020-12-08 10:02

    (int)Math.Round(myNumber, 0)

    0 讨论(0)
  • 2020-12-08 10:03

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

    0 讨论(0)
  • 2020-12-08 10:12

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

    0 讨论(0)
  • 2020-12-08 10:16

    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);
    
    0 讨论(0)
  • 2020-12-08 10:17

    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.)

    0 讨论(0)
提交回复
热议问题