Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number with decimal separator incorrectly cast to Double

Tags:

c#

cultureinfo

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.

like image 302
Arno Smulders Avatar asked Jan 27 '16 09:01

Arno Smulders


1 Answers

If you just want to parse it I would use the dedicated parse methods in which you can set Numberstyles

The following code would throw a FormatException

var culture =new CultureInfo("en-US");
var result = double.Parse("3,3", NumberStyles.AllowDecimalPoint, culture);

For further information see Double.Parse Method

like image 80
Boas Enkler Avatar answered Oct 13 '22 01:10

Boas Enkler