I'm experiencing weird behavior when converting a number to a double, when using culture information.
When converting "3,3"
using the Dutch culture, is handled correctly. If I convert "3,3"
using the US culture, it returns 33
. I was expecting an error. See my example:
static void Main(string[] args)
{
CultureInfo cultureDutch = new CultureInfo("nl-NL");
CultureInfo cultureUS = new CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = cultureDutch;
Console.WriteLine("Input 3,3 --> Expected 3,3");
Console.WriteLine("Output = " + Convert.ToDouble("3,3", cultureDutch));
// Actual result --> 3,3
Console.WriteLine("Input 3,3 --> Expected InvalidCastException");
Console.WriteLine("Output = " + Convert.ToDouble("3,3", cultureUS));
// Actual result --> 33
Console.WriteLine();
Console.WriteLine();
System.Threading.Thread.CurrentThread.CurrentCulture = cultureUS;
Console.WriteLine("Input 3.3 --> Expected InvalidCastException");
Console.WriteLine("Output = " + Convert.ToDouble("3.3", cultureDutch));
// Actual result --> 33
Console.WriteLine("Input 3.3 --> Expected 3.3");
Console.WriteLine("Output = " + Convert.ToDouble("3.3", cultureUS));
// Actual result --> 3.3
Console.ReadLine();
}
What is the correct way to handle this? I would prefer an exception when a decimal (or thousand) separator is invalid.