我该如何圆一个浮点数到最接近INT在C#中?浮点、我该、最接近、数到

2023-09-03 09:27:19 作者:梦醉为红颜丶

在C#中,我该如何圆一个浮点数到最近的诠释?

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

我看到Math.Ceiling和Math.Round,但这些收益小数。难道我用其中的一个,然后转换为一个Int?

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

推荐答案

如果你想圆的最近的 INT:

If you want to round to the nearest int:

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

您也可以使用:

int rounded = Convert.ToInt32(precise);

将使用 Math.Round(X,0)圆和铸造为您服务。它看起来整洁,但略显不清晰海事组织。

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

如果你想圆了

int roundedUp = (int)Math.Ceiling(precise);