What is the best way to convert a double
to an int
? Should a cast be used?
This question is related to
c#
.net
casting
type-conversion
Convert.ToInt32
is the best way to convert
int myInt = (int)Math.Ceiling(myDouble);
Yeah, why not?
double someDouble = 12323.2;
int someInt = (int)someDouble;
Using the Convert
class works well too.
int someOtherInt = Convert.ToInt32(someDouble);
Here is a complete example
class Example
{
public static void Main()
{
double x, y;
int i;
x = 10.0;
y = 3.0;
// cast double to int, fractional component lost (Line to be replaced)
i = (int) (x / y);
Console.WriteLine("Integer outcome of x / y: " + i);
}
}
If you want to round the number to the closer integer do the following:
i = (int) Math.Round(x / y); // Line replaced
label8.Text = "" + years.ToString("00") + " years";
when you want to send it to a label, or something, and you don't want any fractional component, this is the best way
label8.Text = "" + years.ToString("00.00") + " years";
if you want with only 2, and it's always like that
The best way is to simply use Convert.ToInt32
. It is fast and also rounds correctly.
Why make it more complicated?
if you use cast, that is, (int)SomeDouble
you will truncate the fractional part. That is, if SomeDouble
were 4.9999 the result would be 4, not 5. Converting to int doesn't round the number. If you want rounding use Math.Round
I think the best way is Convert.ToInt32
.
My ways are :
- Convert.ToInt32(double_value)
- (int)double_value
- Int32.Parse(double_value.ToString());
Source: Stackoverflow.com