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

∥☆過路亽.° 提交于 2019-12-17 17:55:09

问题


In C#, how do I round a float 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?


回答1:


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



回答2:


Off the top of my head:

float fl = 0.678;
int rounded_f = (int)(fl+0.5f);



回答3:


(int)Math.Round(myNumber, 0)




回答4:


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




回答5:


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




回答6:


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



来源:https://stackoverflow.com/questions/904910/how-do-i-round-a-float-up-to-the-nearest-int-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!