如何舍入到在C#中最接近的整数 [英] How to Round to the nearest whole number in C#

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

问题描述

我如何能圆值是这样的:

How can I round values like this:

1.1 => 1
1.5 => 2
1.9 => 2

Math.Ceiling()是不是我的帮助。任何想法?

Math.Ceiling() is not helping me. Any ideas?

推荐答案

查看官方文档更多。例如:

基本上你给 Math.Round 方法三个参数。

Basically you give the Math.Round method three parameters.


  1. 您要舍入的值。

  2. 您想保留值之后小数位数。

  3. 您可以调用使用AwayFromZero四舍五入的可选参数。没有它,'1.5'四舍五入为12来代替。

样code:

var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2

您需要 MidpointRounding.AwayFromZero 是你想被围捕了0.5的值。不幸的是,这不是默认行为 Math.Round()

You need MidpointRounding.AwayFromZero is you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round().

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

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