如何将 double 转换为最近的整数?
double d = 1.234;
int i = Convert.ToInt32(d);
处理舍入如下:
四舍五入为最接近的32位有符号整数。如果值正好在两个整数中间,返回偶数;也就是说,4.5 转换为 4,5.5 转换为 6。
使用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
Convert.ToInt32()
会执行相同的操作吗?还是只是简单地截去小数点后面的所有内容? - The Muffin ManConvert.ToInt16(NumberToConvert);
。可以将16
替换为32
或64
。 - Cullub你也可以使用以下函数:
//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);
0.5 即可。由于向下转换为 int 始终将数字减小到较低的数字(例如(int)1.7 == 1 ),因此如果您的数字为 0.5 或更高,则添加 0.5 将使其上升到下一个数字,您对 int 的向下转换应返回正确的值。(例如(int)(1.8 +0.5)== 2 )
+ 0.5 * Math.Abs(d)
。 - TaW对于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范围,则会抛出OverflowException
异常。https://learn.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;
}
我正在开发一个带有Int按钮的科学计算器。我发现以下是一个简单且可靠的解决方案:
double dblInteger;
if( dblNumber < 0 )
dblInteger = Math.Ceiling(dblNumber);
else
dblInteger = Math.Floor(dblNumber);
Math.Round有时会产生意外或不良结果,而显式转换为整数(通过强制转换或Convert.ToInt...)通常会对高精度数字产生错误的值。上述方法似乎总是有效。
Math.Round
更好。 - Keith[0,.5)
--向下取整,另一半数字--[.5,1)
--向上取整。即使稍微偏向偶数也会造成偏差,因为它将(.5,1.5
)四舍五入到1,但将[1.5、2.5]
四舍五入到2。 - Jim Balter