Decimal Convert Works in Cloud but not Local Computer

Viewed 71

Goal:
Convert 58.0359401 to decimal without any bug.

Problem:
When I use WPF in my local computer, it doesn't work.
However when I use .Net fiddle (https://dotnetfiddle.net/txro1e) and OnlineGDB (https://onlinegdb.com/HkWbvR-AU) it works.

Questions are:
Do you get the same result if you use the source code in your local computer?
If not, how do you solve it in order to achieve the goal?

If not, how is it possible that two different result could be achieved?

Thank you!

enter image description here

private void Button1_Click(object sender, RoutedEventArgs e)
{
    string test1 = "58.0359401";
    decimal test2 = 58.0359401M;

    decimal output;

    bool isTrue = decimal.TryParse(test1, out output);

    Console.WriteLine(isTrue);
}
1 Answers

decimal.TryParse will use the current default culture unless you specify one. That means if your default culture uses something other than '.' as the decimal separator, but you have a string that does use '.' as the decimal separator, you'll have problems. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        // Change this to "en" and it passes...
        CultureInfo.CurrentCulture = new CultureInfo("fr");
        
        string text = "1.5";
        if (decimal.TryParse(text, out var result))
        {
            Console.WriteLine($"Parsed as: {result}");
        }
        else
        {
            Console.WriteLine("Parsing failed");
        }        
    }
}

If you know that you want to use a specific culture - usually the invariant culture - specify that in the decimal.TryParse call:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        // Even if the current culture is French, the parse succeeds.
        CultureInfo.CurrentCulture = new CultureInfo("fr");
        
        string text = "1.5";
        if (decimal.TryParse(text, NumberStyles.Number,
                             CultureInfo.InvariantCulture, out var result))
        {
            // Prints "Parsed as 1,5" because it uses the default culture
            // for formatting
            Console.WriteLine($"Parsed as: {result}");
        }
        else
        {
            Console.WriteLine("Parsing failed");
        }        
    }
}
Related