How to make InvariantCulture recognize a comma as a decimal separator?
One of articles you've linked says "The invariant culture is internally associated with the English language". So 'InvariantCulture' doesn't mean "try to match any culture". It means: Ignore the local system culture settings and treat this number as formatted in specific standard (basically: English culture standard). So if you want to handle different formats, your options here are:
- Try parsing the number without specyfing culture (will use local OS culture info), then try with InvariantCulture, then maybe try some fallback culture you expect the number to be formatted with.
- Replace ',' with '.' and parse the number string using Invariant culture. You may want to make sure that the number string does not contain decimal group separators (like 1,000.00).
default
Working as a Software Developer writing various C#, trying out react and typescript and stuff.
Updated on July 18, 2022Comments
-
default almost 2 years
How do I parse
1,2
withSingle.Parse
? The reason of asking is because, when I am usingCultureInfo.InvariantCulture
I don't get 1.2 as I would like, but rather 12.Shouldn't "Invariant Culture" ignore the culture?
Consider the following example:
using System; using System.Globalization; public class Program { public static void Main() { Console.WriteLine(Single.Parse("1,2", CultureInfo.InvariantCulture)); Console.WriteLine(Single.Parse("1.2", CultureInfo.InvariantCulture)); float value; Console.WriteLine(Single.TryParse("1,2", NumberStyles.Float, CultureInfo.InvariantCulture, out value)); Console.WriteLine(Single.TryParse("1,2", out value)); Console.WriteLine(value); } }
The output of this will be
12
1.2
False
True
12But I was expecting:
1.2
1.2
True
True
1.2Based on my reading of
InvariantCulture
I should get that result, however I am not.