What is the best way to convert a double
to an int
? Should a cast be used?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
if you use cast, that is,
(int)SomeDouble
you will truncate the fractional part. That is, ifSomeDouble
were 4.9999 the result would be 4, not 5. Converting to int doesn't round the number. If you want rounding useMath.Round
Here is a complete example
If you want to round the number to the closer integer do the following:
I think the best way is
Convert.ToInt32
.when you want to send it to a label, or something, and you don't want any fractional component, this is the best way
if you want with only 2, and it's always like that
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 ofdouble
. A cast fromdouble
toint
won't throw an exception if the value is outside the range ofint
in an unchecked context, whereas a call toConvert.ToInt32(double)
will. The result of the cast (in an unchecked context) is explicitly undefined if the value is outside the range.int myInt = (int)Math.Ceiling(myDouble);