c# - 如何在 C# 中将 float 向上舍入到最接近的整数?

标签 c# .net rounding

在 C# 中,如何将 float 向上舍入到最接近的整数?

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

最佳答案

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

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

您还可以使用:

int rounded = Convert.ToInt32(precise);

这将使用 Math.Round(x, 0); 为您进行舍入和转换。它看起来更整洁,但在 IMO 上不太清晰。


如果您想向上取整:

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

关于c# - 如何在 C# 中将 float 向上舍入到最接近的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/904910/

相关文章:

C#:将自定义集合转储到 csv 文件的最简单方法

c# - Entity Framework - 打印 EntityValidationErrors 以记录

c# - 如何制作前向词,后向词,将下划线视为单词的一部分?

c# - .NET 接口(interface)上正确的 xml 注释

c# - 解析器错误消息 : Could not create type 'xxx'

c# - 带有 View.CurrentItem 的奇怪 CommandParameter

java - 对数字(float)进行舍入以将其存储为 int,而不使用像 math.round() 这样的 math.packe

c - 在 C 中是否有舍入 float 的函数,还是我需要自己编写?

c# - 子文件夹中位图的 URI (c# wpf)

java-me - J2ME有舍入功能吗?