[c#] How might I convert a double to the nearest integer value?

How do you convert a double into the nearest int?

This question is related to c# rounding

The answer is


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

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

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.


Methods in other answers throw OverflowException if 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_

int result = 0;
try {
    result = Convert.ToInt32(value);
}
catch (OverflowException) {
    if (value > 0) result = int.MaxValue;
    else result = int.Minvalue;
}

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.


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 .5 to your value before downcasting. As downcasting to int always drops to the lower number (e.g. (int)1.7 == 1), if your number is .5 or higher, adding .5 will bring it up into the next number and your downcast to int should return the correct value. (e.g. (int)(1.8 + .5) == 2)


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

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.