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

后端 未结 8 1934
傲寒
傲寒 2020-12-08 08:45

How do you convert a double into the nearest int?

8条回答
  •  借酒劲吻你
    2020-12-08 09:23

    For Unity, use 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); }
    

提交回复
热议问题