You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据货币代码/符号将字符串格式化为货币格式

根据货币代码格式化货币字符串

直接通过CultureInfo.CreateSpecificCulture("USD")无法生效,因为CultureInfo是基于区域设置(Locale)而非货币代码创建的。以下是两种可行的实现方式:

方法一:通过货币代码匹配对应的区域设置

遍历所有可用的区域设置,找到对应货币代码的CultureInfo,再用它来格式化:

public static CultureInfo GetCultureByCurrencyCode(string currencyCode)
{
    foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
    {
        RegionInfo region = new RegionInfo(culture.LCID);
        if (region.ISOCurrencySymbol.Equals(currencyCode, StringComparison.OrdinalIgnoreCase))
        {
            return culture;
        }
    }
    throw new ArgumentException($"未找到对应货币代码 {currencyCode} 的区域设置");
}

使用示例:

decimal amount = 1234.56m;
string usdFormatted = amount.ToString("C", GetCultureByCurrencyCode("USD"));
// 输出:$1,234.56

注意:一种货币可能对应多个区域(比如USD对应en-US、es-US),此方法会返回第一个匹配的区域设置。如果需要指定偏好区域,可以在遍历中增加筛选条件(比如优先en-US)。

方法二:手动构建货币格式规则

如果需要完全自定义格式,不受区域设置影响,可以手动创建NumberFormatInfo并指定货币相关属性:

public static string FormatCurrencyByCode(decimal value, string currencyCode)
{
    var currencyConfigs = new Dictionary<string, (string Symbol, int DecimalDigits)>
    {
        {"USD", ("$", 2)},
        {"EUR", ("€", 2)},
        {"GBP", ("£", 2)},
        {"JPY", ("¥", 0)}
        // 可根据需求扩展更多货币配置
    };

    if (!currencyConfigs.TryGetValue(currencyCode, out var config))
    {
        throw new ArgumentException($"不支持的货币代码:{currencyCode}");
    }

    NumberFormatInfo nfi = new NumberFormatInfo
    {
        CurrencySymbol = config.Symbol,
        CurrencyDecimalDigits = config.DecimalDigits,
        CurrencyGroupSeparator = ",",
        CurrencyDecimalSeparator = "."
    };

    return value.ToString("C", nfi);
}

使用示例:

decimal amount = 1234.56m;
string usdFormatted = FormatCurrencyByCode(amount, "USD");
// 输出:$1,234.56

此方法的优势是格式完全可控,但需要维护货币的配置信息,适合对格式有固定要求的场景。

内容的提问来源于stack exchange,提问作者tapizquent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:54:48