My current CultureInfo is "CultureInfo("de-DE")" (by default setting), when I parse a str, it would be non-english result.
So could I set InvariantCulture default globally(init)?
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
// new CultureInfo("de-DE")
Debug.Log(float.Parse("0.11")); // 11
CodePudding user response:
The parser must know which decimal separator should be used. Normally the CultureInfo.InvariantCulture
should use a .
but..
You could pass an English culture as argument:
Debug.Log(float.Parse("0.11", new CultureInfo("en-US")); // 0.11
This won't affect the rest of the program.
CodePudding user response:
Yes, you can do that, but I would not recommend it. It will confuse users, when they expect to enter numbers in their native format (using a "," as decimal separator for the german culture).
Instead of globally setting the culture to invariant, you should always use the overloads to Parse
that take a culture as argument, explicitly specifying whether at this particular location you expect local input (the data typically comes from the UI) or invariant input (the data comes from a file or database). If you get used to this, you'll avoid a lot of culture-dependent errors.
The same applies for the related methods ToString()
and TryParse()
.