Method to parse decimals with various decimal/radix separators

醉酒当歌 提交于 2021-01-29 06:52:37

问题


I do a lot of file parsing, which involves parsing data types like decimal. To help make the code more readable, I've been using the following method:

public static decimal? ToDecimal(this string data)
{
    decimal result;
    if (decimal.TryParse(data, NumberStyles.Integer | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result))
        return result;

    return null;
}

This works fine for decimals which are represented with a full-stop/period as the decimal separator. However, I'd like this function to work with other standard decimal separators, particularly the comma. (I read that there is also an Arabic decimal separator: http://en.wikipedia.org/wiki/Decimal_mark#Other_numeral_systems, but that presumably relies on being able to parse the eastern arabic numerals too).

The Culture.CurrentCulture wouldn't be appropriate because the data is not necessarily created on the machine that is doing the processing. So I've now got this:

private static CultureInfo CreateCultureWithNumericDecimalSeparator(string separator)
{
    var cultureInfo = (CultureInfo)CultureInfo.InvariantCulture.Clone();
    cultureInfo.NumberFormat.NumberDecimalSeparator = separator;
    return cultureInfo;
}

private static CultureInfo[] cultureInfos = new CultureInfo[]
{
    CultureInfo.InvariantCulture,
    CreateCultureWithNumericDecimalSeparator(",") // Normal comma
};

public static decimal? ToDecimal(this string data)
{
    foreach (CultureInfo cultureInfo in cultureInfos)
    {
        decimal result;
        if (decimal.TryParse(data, NumberStyles.Integer | NumberStyles.AllowDecimalPoint, cultureInfo, out result))
            return result;
    }

    return null;
}

This works, but parsing twice, especially given that TryParse is checking all sorts of settings (thousand separators, hex specifiers, currency symbols, exponents, etc) seems a little heavy. It's probably not a performance issue, but I'm curious to know if there's a more efficient method to do this, or possibly even an existing method within the framework? And maybe even a method that could cope with other numeral systems in modern use? Thanks.


回答1:


It seems that that the framework doesn't provide this directly. Interestingly, answers to another question suggest that the framework doesn't provide any mechanism for parsing Eastern Arabic numerals, even with the culture set. As the Eastern Arabic numerals requirement was just theoretical for my app, I'm sticking with the code I've already got above. If I implement anything more specific, I'll post it!



来源:https://stackoverflow.com/questions/11889694/method-to-parse-decimals-with-various-decimal-radix-separators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!