I am at an internship where there is parsing done on strings read from a XML file. Specifically the strings are representations of decimal numbers. A problem arises when I try to parse a decimal string formatted differently than the ones that have comma separators and a decimal point. For example the way that nations format their decimal numbers differently:
- France: 1 234 567,89 == 1,234,567.89
- Germany: 1.234.567,89 == 1,234,567.89
- Australia: 1 234 567.89 == 1,234,567,89
I'm pretty sure that's how those countries can represent decimal numbers. If not sorry. Point is 1,234,567.89 may be represented many ways.
What I would like to do is ensure that whatever string representation of a decimal number I try to parse it ought to come out 1,234,567.89.
I thought that a good way to go about this would be to use the double.TryParse()
method but I have been unable to get it to work.
Here is what I got in just a little test application:
double num;
Console.WriteLine(double.TryParse("1 234 567,89", NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out num).ToString());
Console.WriteLine(num.ToString());
Console.WriteLine(double.TryParse("1.234.567,89", NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out num).ToString());
Console.WriteLine(num.ToString());
Console.WriteLine(double.TryParse("1 234 567.89", NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out num).ToString());
Console.WriteLine(num.ToString());
Where all I do is check to see that TryParse
worked and then print the number. In this case TryParse always outputs false. The false means that TryParse
caught a FormatException
and it obviously failed converting the string to a double.
Does this look right or am I just completely confused about what I am doing?
I'm under the impression that by saying NumberStyles.Any
it indicates that the string can be in any form of a decimal number. I am also under the impression that saying CultureInfo.InvariantCulture.NumberFormat
returns the formatting information of numbers that are culturally independent. In other words it will create a decimal of the form 1,234,567.89.
Thanks for taking the time to read my problem. Any help would be much appreciated.