C# parsing float from string

后端 未结 3 566
刺人心
刺人心 2021-01-12 23:26

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

3条回答
  •  独厮守ぢ
    2021-01-13 00:10

    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:

    private static readonly NumberFormatInfo DecimalSeparatorFormat = new NumberFormatInfo { NumberDecimalSeparator = ".", NumberGroupSeparator = "," };
    private static readonly NumberFormatInfo CommaSeparatorFormat = new NumberFormatInfo { NumberDecimalSeparator = ",", NumberGroupSeparator = "." };
    

    And then try parsing the number through your known accepted formats:

      if (!Single.TryParse(unparsedValue, NumberStyles.Float, DecimalSeparatorFormat, out parsedValue) && !Single.TryParse(unparsedValue, NumberStyles.Float, CommaSeparatorFormat, out parsedValue))
        throw new FormatException("Number format not supported");
    

    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).

提交回复
热议问题