convert double to int

2020-01-24 07:12发布

What is the best way to convert a double to an int? Should a cast be used?

10条回答
等我变得足够好
2楼-- · 2020-01-24 07:52

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

查看更多
神经病院院长
3楼-- · 2020-01-24 07:55

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
查看更多
我只想做你的唯一
4楼-- · 2020-01-24 07:55

I think the best way is Convert.ToInt32.

查看更多
smile是对你的礼貌
5楼-- · 2020-01-24 07:56
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

查看更多
我想做一个坏孩纸
6楼-- · 2020-01-24 07:57

You can use a cast if you want the default truncate-towards-zero behaviour. Alternatively, you might want to use Math.Ceiling, Math.Round, Math.Floor etc - although you'll still need a cast afterwards.

Don't forget that the range of int is much smaller than the range of double. A cast from double to int won't throw an exception if the value is outside the range of int in an unchecked context, whereas a call to Convert.ToInt32(double) will. The result of the cast (in an unchecked context) is explicitly undefined if the value is outside the range.

查看更多
▲ chillily
7楼-- · 2020-01-24 08:03

int myInt = (int)Math.Ceiling(myDouble);

查看更多
登录 后发表回答