如何在 C# 中将浮点数四舍五入到最近的整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/904910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:29:09  来源:igfitidea点击:

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

c#.netrounding

提问by

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

在 C# 中,如何将浮点数四舍五入到最近的 int?

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

我看到 Math.Ceiling 和 Math.Round,但这些返回一个小数。我是否使用其中之一然后转换为 Int?

采纳答案by Matt Brindley

If you want to round to the nearestint:

如果你想四舍五入到最近的整数:

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);为您舍入和投射。它看起来更整洁,但 IMO 的清晰度稍差。



If you want to round up:

如果你想圆

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

回答by joshcomley

(int)Math.Round(myNumber, 0)

(int)Math.Round(myNumber, 0)

回答by Mike Tunnicliffe

Off the top of my head:

在我的头顶:

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

回答by dan-gph

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. (You won't get a case, for instance, where Round returns 4.999... instead of 5.)

是的。这样做没有问题。Decimals 和 doubles 可以精确表示整数,因此不会出现表示错误。(例如,您不会遇到 Round 返回 4.999... 而不是 5 的情况。)

回答by JulianR

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

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

回答by Joe

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

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