I'm trying to make my program more compatible, for that I've ended up changing a lot of little things for example,
Using textBox.Text = Convert.ToString(value)
instead of = "value"
Getting the current user decimal separator and using it replace
on a tryparse
char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
float.TryParse(str.Replace(",", sepdec.ToString()).Replace(".", sepdec.ToString()), out testvariable;
But these solutions are hard to implement when you have already coded most of your program without worrying about it.
So I'm trying to find ways to make the whole code compatible, without having to edit every tryparse
and every textbox
I've tried to do the following:
//Get the current user decimal separator before the program initializes
char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
//Create a current culture clone and change the separator to whatever the user has in his regional options, before the initializing the component
public Form1()
{
System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = sepdec.ToString();
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
InitializeComponent();
}
But I've tested this, and it's not really doing anything. Wasn't it supposed to make the program understand something like ok, now you use dot as your decimal separator altough you have values in textBox as "2,5"
?
ok, now you use dot as your decimal separator altough you have values in textBox as "2,5"
Exactly.
float.TryParse
method uses your CurrentCulture
settings if you don't use any IFormatProvider
with it.
If you try to parse "2,5"
to float without any IFormatProvider
, your CurrentCulture
has to have ,
as a NumberDecimalSeparator
.
If you try to parse "2.5"
to float, you either use a culture as an another parameter which already has . as a NumberDecimalSeparator
(like InvariantCulture
), or you can .Clone()
your CurrentCulture
(as you did) and set it's NumberDecimalSeparator
property to .
and use this cloned culture as an another parameter in float.TryParse
overload.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments