ら、どのように変換するdoubleもっとも近い整数値にはどのようなものか?

StackOverflow https://stackoverflow.com/questions/633335

  •  10-07-2019
  •  | 
  •  

質問

どんなに変換するダブルの最寄りの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ビット符号付き整数に丸められます。値が中間の場合   2つの整数の間では、偶数が返されます。つまり、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)

この回答が誰にとっても役立つことを願っています。

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は、予期しないまたは望ましくない結果を生成することがあり、整数への明示的な変換(キャストまたはConvert.ToInt ...を使用)により、高精度の数値に対して誤った値が生成されることがよくあります。上記の方法は常に機能するようです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top