简体   繁体   English

如何将浮点数向上舍入到 C# 中最近的整数?

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

In C#, how do I round a float upwards to the nearest int?在 C# 中,如何将浮点数向上舍入到最近的整数?

I see Math.Ceiling and Math.Round, but these returns a decimal.我看到 Math.Ceiling 和 Math.Round,但这些返回一个小数。 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);

You can also use:您还可以使用:

int rounded = Convert.ToInt32(precise);

Which will use Math.Round(x, 0);这将使用Math.Round(x, 0); to round and cast for you.为你圆和铸造。 It looks neater but is slightly less clear IMO.它看起来更整洁,但 IMO 的清晰度稍差。


If you want to round up :如果你想圆

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

Off the top of my head:在我的头顶:

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

(int)Math.Round(myNumber, 0)

最简单的方法是向其添加0.5f ,然后将其转换为 int。

Do I use one of these then cast to an Int?我是否使用其中之一然后转换为 Int?

Yes.是的。 There is no problem doing that.这样做没有问题。 Decimals and doubles can represent integers exactly, so there will be no representation error. Decimals 和 doubles 可以精确表示整数,因此不会出现表示错误。 (You won't get a case, for instance, where Round returns 4.999... instead of 5.) (例如,您不会遇到 Round 返回 4.999... 而不是 5 的情况。)

您可以转换为 int,前提是您确定它在 int 的范围内(Int32.MinValue 到 Int32.MaxValue)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM