C# 如何将 double 转换为最接近的整数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/633335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:07:36  来源:igfitidea点击:

How might I convert a double to the nearest integer value?

c#rounding

提问by leora

How do you convert a double into the nearest int?

你如何将双精度转换为最近的整数?

采纳答案by nickf

Use Math.round(), possibly in conjunction with MidpointRounding.AwayFromZero

使用Math.round(),可能与MidpointRounding.AwayFromZero

eg:

例如:

Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3

回答by John Sheehan

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

Reference

参考

Handles rounding like so:

像这样处理舍入:

rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

四舍五入到最接近的 32 位有符号整数。如果 value 介于两个整数之间,则返回偶数;即4.5转4,5.5转6。

回答by John Sheehan

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

回答by Mark Jones

I'm developing a scientific calculator that sports an Int button. I've found the following is a simple, reliable solution:

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

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

Math.Round sometimes produces unexpected or undesirable results, and explicit conversion to integer (via cast or Convert.ToInt...) often produces wrong values for higher-precision numbers. The above method seems to always work.

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

回答by szymcio

You can also use function:

您还可以使用功能:

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

Depending on the architecture it is several times faster.

根据架构,它要快几倍。

回答by Trent

I know this question is old, but I came across it in my search for the answer to my similar question. I thought I would share the very useful tip that I have been given.

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

When converting to int, simply add .5to your value before downcasting. As downcasting to intalways drops to the lower number (e.g. (int)1.7 == 1), if your number is .5or higher, adding .5will bring it up into the next number and your downcast to intshould return the correct value. (e.g. (int)(1.8 + .5) == 2)

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

回答by zwcloud

For Unity, use Mathf.RoundToInt.

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

Source

来源

public static int RoundToInt(float f) { return (int)Math.Round(f); }

回答by Gru

Methods in other answers throw OverflowExceptionif the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_

OverflowException如果浮点值超出 Int 范围,则其他答案中的方法将抛出。https://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;
}