我该如何圆一个浮点数到最接近INT在C#中? [英] How do I round a float up to the nearest int in C#?

查看:213
本文介绍了我该如何圆一个浮点数到最接近INT在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于我该如何圆一个浮点数到最接近INT在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆