Answers:
Math.round()结合使用,可能与MidpointRounding.AwayFromZero
例如:
Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3double d = 1.234;
int i = Convert.ToInt32(d);这样处理舍入:
舍入到最接近的32位有符号整数。如果值在两个整数之间,则返回偶数;否则,返回偶数。即4.5转换为4,5.5转换为6。
Math.Round,它根据需要返回int。
                    [0,.5)向下,正好舍入一半的数字[.5,1)--向上。四舍五入到稍微偏置偶数,因为它四舍五入(.5,1.5)到1,但[1.5,2.5]到2
                    您还可以使用功能:
//Works with negative numbers now
static int MyRound(double d) {
  if (d < 0) {
    return (int)(d - 0.5);
  }
  return (int)(d + 0.5);
}根据体系结构,它要快几倍。
double d;
int rounded = (int)Math.Round(d);我知道这个问题很旧,但是在寻找类似问题的答案时遇到了它。我以为我会分享给我的非常有用的提示。
转换为int时,只需.5在向下转换前添加您的值即可。由于向下转换int始终下降到较低的数字(例如(int)1.7 == 1),因此,如果您的数字大于或等于该数字,则.5添加.5将其带入下一个数字,而向下转换至的数字int应返回正确的值。(例如(int)(1.8 + .5) == 2)
+ 0.5 * Math.Abs(d)
                    OverflowException如果float值超出Int范围,则抛出其他答案中的方法。https://docs.microsoft.com/zh-cn/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_
int result = 0;
try {
    result = Convert.ToInt32(value);
}
catch (OverflowException) {
    if (value > 0) result = int.MaxValue;
    else result = int.Minvalue;
}对于Unity,请使用Mathf.RoundToInt。
using UnityEngine;
public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.0f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.2f));
        // Prints 11
        Debug.Log(Mathf.RoundToInt(10.7f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.5f));
        // Prints 12
        Debug.Log(Mathf.RoundToInt(11.5f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.0f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.2f));
        // Prints -11
        Debug.Log(Mathf.RoundToInt(-10.7f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.5f));
        // Prints -12
        Debug.Log(Mathf.RoundToInt(-11.5f));
    }
}public static int RoundToInt(float f) { return (int)Math.Round(f); }我正在开发一款具有Int按钮的科学计算器。我发现以下是一个简单,可靠的解决方案:
double dblInteger;
if( dblNumber < 0 )
   dblInteger = Math.Ceiling(dblNumber);
else
   dblInteger = Math.Floor(dblNumber);Math.Round有时会产生意外或不希望的结果,并且显式转换为整数(通过强制转换或Convert.ToInt ...)通常会为更高的数字产生错误的值。上面的方法似乎总是可行。
Convert.ToInt32()做同样的事情,还是只是在小数点后去除所有内容?