Parse value with Currency symbol

前端 未结 5 1916
耶瑟儿~
耶瑟儿~ 2021-01-21 13:58

I have looked to multiple SO questions on parsing currency, the best (recommended) way seems to be the one I\'m trying below:

var payout = decimal.Parse(\"$2.10\         


        
5条回答
  •  [愿得一人]
    2021-01-21 14:25

    Similar approach @un-lucky mentioned as one of the answer, I tried making it generic and work for every Symbol/Format

    public static decimal ParseCurrencyWithSymbol(string input)
    {
        var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures)
            .GroupBy(c=> c.NumberFormat.CurrencySymbol)
            .ToDictionary(c=> c.Key, c=>c.First());
    
    
        var culture = cultures.FirstOrDefault(c=>input.Contains(c.Key));
    
        decimal result = 0;
        if(!culture.Equals(default(KeyValuePair)))
        {
            result = decimal.Parse(input, NumberStyles.Currency | NumberStyles.AllowDecimalPoint, culture.Value);
        }
        else
        {
            if( !decimal.TryParse(input, out result))
            {
                throw new Exception("Invalid number format");
            }
        }
    
        return result;
    }
    

    Usage

    decimal output = ParseCurrencyWithSymbol("$2.10");
    

    Working Code

提交回复
热议问题