C# and NumberDecimalSeparator

When developing an application with C# (also VB), decimal separator can be a nightmare for developer. User can enter a numeric value with dot or comma. Like 2.5 or 2,5

When we try to parse this value to a numeric value, user separator can be a problem.

For example on my computer when i run the following code block:
    string valueWithDot = "2.5";
    string valueWithComma = "2,5";
    
    Console.WriteLine(decimal.Parse(valueWithDot));
    Console.WriteLine(decimal.Parse(valueWithComma));
i see following results on the console

25
2,5


Here is the tricky function that i created to handle this problem :
    public static void FixNumberDecimalSeparator(ref string value)
    {
        value = value.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
                     .Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
    }
When i use this function in the main function :
    string valueWithDot = "2.5";
    string valueWithComma = "2,5";

    FixNumberDecimalSeparator(ref valueWithDot);
    FixNumberDecimalSeparator(ref valueWithComma);

    Console.WriteLine(decimal.Parse(valueWithDot));
    Console.WriteLine(decimal.Parse(valueWithComma));
i see following results on the console

2,5
2,5


I hope this function will be useful for you.

0 comments:

Post a Comment