在 C # 中,如何将浮点数向上舍入到最近的整型数?
我看到数学了。天花板和数学。四舍五入,但返回的是小数。我是否要使用其中一个然后转换为 Int?
(int)Math.Round(myNumber, 0)
Off the top of my head:
float fl = 0.678; int rounded_f = (int)(fl+0.5f);
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.
Math.Round(x, 0);
If you want to round up:
int roundedUp = (int)Math.Ceiling(precise);
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.)
The easiest is to just add 0.5f to it and then cast this to an int.
0.5f
You can cast to an int provided you are sure it's in the range for an int (Int32.MinValue to Int32.MaxValue).