Home > OS >  Can't convert value from string using int.Parse
Can't convert value from string using int.Parse

Time:03-09

I'm studying c# from Linkedin Learning, and in a lesson, the professor code worked great in the video, but the exact same file doesn't work for me, returning the error:

Input string was not in a correct format.

This is the code that doesnt work:

using System; 
using System.Globalization;

namespace Parsing {
    class Program
    {
        static void Main(string[] args)
        {
            string numStr = "2.00";

            int targetNum=0;
            try {

                targetNum = int.Parse(numStr, NumberStyles.Float);
                Console.WriteLine(targetNum);

            }
            catch(Exception e) {
                Console.Write(e.Message);
                
            }
         
            bool succeeded = false;
            
            if (succeeded) {
                Console.WriteLine($"{targetNum}");
            }
        }
    } 
}

This, however, does work:

using System; 
using System.Globalization;

namespace Parsing {
    class Program
    {
        static void Main(string[] args)
        {
            string numStr = "2";

            int targetNum=0;
            try {

                targetNum = int.Parse(numStr, NumberStyles.Float);
                Console.WriteLine(targetNum);

            }
            catch(Exception e) {
                Console.Write(e.Message);
                
            }
         
            bool succeeded = false;
            
            if (succeeded) {
                Console.WriteLine($"{targetNum}");
            }
        }
    } 
}

Anyone have a light to shine on why the other code doesn't work?

CodePudding user response:

Your profile says you're based in Brazil and in Brazil "two and a half" is "2,5", not "2.5".

If you run your code with "2,00" it should work.

Here's an example with different cultures:

foreach(var two in new []{"2.00", "2,00"})
foreach(var culture in new []{"pt-BR", "en-AU"})
{
    bool ok = int.TryParse(two, System.Globalization.NumberStyles.Float, new System.Globalization.CultureInfo(culture), out var i);
    Console.WriteLine($"For '{culture}' '{two}' is {(ok ? "OK" : "not OK")}");
}

This prints:

For 'pt-BR' '2.00' is not OK
For 'en-AU' '2.00' is OK
For 'pt-BR' '2,00' is OK
For 'en-AU' '2,00' is not OK
  • Related