如何将浮点数向上舍入到C#中最接近的整数? [英] How do I round a float upwards to the nearest int in C#?

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

问题描述

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

In C#, how do I round a float upwards 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); 为您舍入并投射.它看起来更整洁,但IMO却不太清晰.

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

这篇关于如何将浮点数向上舍入到C#中最接近的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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