I'm reading numbers from XML files. Other numbers are with a comma separator (0,1111) and others with dot (0.1111). How do I parse these numbers so I get the desired result in the end? I tried using float.Parse(reader.Value, System.Globalization.CultureInfo.InvariantCulture);
but it doesn't work. For example I have reader.Value = "0,01119703" and is parsed as 1119703.0.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- Correctly parse PDF paragraphs with Python
- 求获取指定qq 资料的方法
Is there anything in the XML files that will tell you which format is being used? There's not a built-in way in .NET to have two different allowed decimal separators. If there's nothing telling you which format a number is going to be in, then you could always check to see whether the string contains a period or a comma, and create a NumberFormatInfo with that as the decimal separator. Of course, this won't work if any of the numbers have a period or comma as a thousands separator.
I don't believe that it is possible to work with two different decimal separators at the same time. I think I would just use Replace() to change any commas into dots.
Not sure this is the greatest solution, but perhaps you could rely on a set of known "Custom" number formats. For instance, you could declare two custom number formats (either from scratch or based off of a known format) such as:
And then try parsing the number through your known accepted formats:
This assumes that you have a finite number of known formats, if your inputs can truly be in any culture, then you may be out of luck with finding a great solution.
The one win with this approach is you are at least being explicit in the formats you are able to support rather than relying on a simple string replace (which may result in an invalid format).