I stumbled upon this strange behavior of Convert class and I want to share.
Convert.ToInt
(16,32,64) methods when used on double
or decimal
type round in a strange way:
from msdn:
converted value is rounded to the nearest 16-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.
This is a really strange behavior and it can lead to hard to find bugs.
I looked with reflector to analyzed the code but it is an extern
method:
//Convert.ToInt32
[SecuritySafeCritical, __DynamicallyInvokable]
public static int ToInt32(decimal value)
{
return decimal.FCallToInt32(value);
}
//decimal
[MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
internal static extern int FCallToInt32(decimal d);
I know that Convert
class is meant to converts a base data type to another base data type and it should not be used for rounding value but you will agree that we would have to expect a standard rounding.
My question is why this behavior and why it is not stamped with big red fonts on MSDN