[C#] double을 가장 가까운 정수 값으로 어떻게 변환 할 수 있습니까?

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다음 숫자로 추가 하고 다운 캐스트 int는 올바른 값을 반환해야합니다. (예를 들어 (int)(1.8 + .5) == 2)


답변

OverflowException부동 소수점 값이 Int 범위를 벗어나면 다른 답변의 메소드가 throw 됩니다. 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;
}


답변

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