The problem: Let's assume you are using a dot "." as a decimal separator in your regional setting and have coded a string with a comma.
string str = "2,5";
What happens when you decimal.TryParse(str, out somevariable);
it?
somevariable
will assume 0.
What can you do to solve it?
1- You can
decimal.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out somevariable);
And it will return 25, and not 2.5 which is wrong.
2- You can
decimal.TryParse(str.Replace(",","."), out num);
And it will return the proper value, BUT, if the user uses ","
as a decimal separator it will not work.
Possible solution that I can't make it work:
Get the user decimal separator in regional settings:
char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
And make somehow the replace from ",",sepdec
, that way it would stay a comma if its a comma, and replace by an actual dot if the user uses dots.
Hints?
Edit: Many users posted useful information, lately, using the arguments NumberStyles.Any, CultureInfo.GetCultureInfo("pt-PT")
on a tryParse
wouldn't work if your separator is set to "," So it pretty much doesnt fullfill the premise of making a tryparse "universal".
I'll work around this, if anyone has more hints you'r welcome
2,5
may be interpreted differently in different countries. All you need is using the correct CultureInfo – EZIstring str = "2,500";
what value does this represent now? 2.5 or 2500.0 ? There is no way to tell, unless you know the culture that is associated with this string value. – Alexcan I change it only in the tryparse scope?
Of course. See the methodCultureInfo.GetCultureInfo
. – EZIfalse
as an error, and handle it as appropriate for your program. For instance:if (decimal.TryParse(str, out val)) { Console.WriteLine("val: " + val); } else { Console.WriteLine(str + " cannot be parsed!"); }
Note how the value ofval
is only used in theif
branch that gets taken whenTryParse
returnstrue
. This tells the user that the value ofstr
is incorrect, and that the user should have used a different value. It generally doesn't make sense to treat gibberish such as "avh5v3l" as a validdecimal
with a value of zero. – user743382