我怎样才能将double转换为最接近的整数值?

时间:2009-03-11 04:32:05

标签: c# rounding

如何将double转换为最接近的int?

8 个答案:

答案 0 :(得分:235)

double d = 1.234;
int i = Convert.ToInt32(d);

Reference

像这样处理舍入:

  

四舍五入到最近的32位有符号整数。如果价值是中途   在两个整数之间,返回偶数;也就是说,4.5   转换为4,并将5.5转换为6.

答案 1 :(得分:75)

使用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) ==> 3

答案 2 :(得分:35)

您也可以使用功能:

//Works with negative numbers now
static int MyRound(double d) {
  if (d < 0) {
    return (int)(d - 0.5);
  }
  return (int)(d + 0.5);
}

取决于架构,速度要快几倍。

答案 3 :(得分:11)

double d;
int rounded = (int)Math.Round(d);

答案 4 :(得分:4)

我知道这个问题很老,但我在寻找类似问题的答案时遇到了这个问题。我想我会分享我给出的非常有用的提示。

转换为int时,只需在向下转换前将.5添加到您的值。由于向下转换为int总是下降到较低的数字(例如(int)1.7 = 1),如果你的数字是.5或更高,添加.5将把它带到下一个数字,你的downcast到int应该返回正确的值。 (例如(int)(1.8 + .5)= 2)

我希望这个答案对任何人都有帮助。

答案 5 :(得分:0)

对于Unity,请使用Mathf.RoundToInt

interface I
{
    [Obsolete("Use NewMethod instead.")]
    void OldMethod();
    void NewMethod();
}

class Explicit : I
{
    public void NewMethod() { throw new NotImplementedException(); }
    public void OldMethod() { throw new NotImplementedException(); }
}

class Implicit : I
{
    void I.NewMethod() { throw new NotImplementedException(); }
    void I.OldMethod() { throw new NotImplementedException(); }
}

Source

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

答案 6 :(得分:0)

如果float值超出Int范围,则其他答案中的方法将引发OverflowExceptionhttps://docs.microsoft.com/en-us/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;
}

答案 7 :(得分:-1)

我正在开发一个体育Int按钮的科学计算器。我发现以下是一个简单,可靠的解决方案:

double dblInteger;
if( dblNumber < 0 )
   dblInteger = Math.Ceiling(dblNumber);
else
   dblInteger = Math.Floor(dblNumber);

Math.Round有时会产生意外或不良结果,显式转换为整数(通过强制转换或转换.ToInt ...)通常会为更高精度的数字生成错误的值。上述方法似乎总能奏效。

相关问题