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

有帮助吗?

解决方案

使用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

其他提示

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

参考

像这样处理舍入:

  

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

您也可以使用功能:

//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将把它带到下一个数字,你的downcast到int应该返回正确的值。 (例如(int)(1.8 + .5)= 2)

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top