How might I convert a double to the nearest integer value?
Question
How do you convert a double into the nearest int?
Solution
Use Math.round()
, possibly in conjunction with 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
OTHER TIPS
double d = 1.234;
int i = Convert.ToInt32(d);
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.
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.
double d;
int rounded = (int)Math.Round(d);
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 hope this answer is helpful to anyone.
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));
}
}
public static int RoundToInt(float f) { return (int)Math.Round(f); }
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.