用货币符号解析值 [英] Parse value with Currency symbol

查看:52
本文介绍了用货币符号解析值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了多个有关解析货币的 SO 问题,最好的(推荐的)方法似乎是我在下面尝试的方法:

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", NumberStyles.Currency | NumberStyles.AllowDecimalPoint);

但是,它抛出异常:输入字符串的格式不正确.

However, it throws and exception: Input string is not in the correct format.

我不知道我做错了什么?

I don't know what I'm doing wrong?

编辑

感谢您的回答.附加信息:我给出的硬编码货币价值只是一个例子.我有一份货币清单:

Thanks for the answers. Additional info: the hard-coded currency value I gave was just an example. I have a list of currencies:

€2,66

$2.10

5.55 美元

我无法提前确定文化信息.有什么想法吗?

I cannot determine the culture info in advance. Any ideas?

推荐答案

类似方法 @un-lucky 提到作为答案之一,我尝试使其通用并适用于每个 Symbol/格式

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<string,CultureInfo>)))
    {
        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;
}

使用

decimal output = ParseCurrencyWithSymbol("$2.10");

工作 代码

这篇关于用货币符号解析值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆