繁体   English   中英

如何获取指定货币和文化的格式字符串

[英]How to get the format string for a specified currency and culture

我有显示货币金额的 SSRS 报告。 他们需要同时具备文化意识和货币意识。 一些报告在同一张表中显示不同的货币。 我对文化意识没有任何问题。 麻烦的是货币格式。 重要的是,当我导出到 Excel 时,这些货币字段中的值必须可以按数字排序。 这意味着单元格值必须是数字,所以我不能使用许多其他帖子最终使用的 normal.ToString("C",culture) 函数。 我需要在字段中保留数值并将.NET 的格式字符串应用于数字(例如“'$'#,0.00;('$'#,0.00)”)。 这样,Excel 会将值视为用于排序目的的数字,但会显示格式正确的货币。

是否可以使用代码修改 NumberFormatInfo 实例,然后以某种方式返回格式化程序的字符串值,例如“'€'#,0.00;('€'#,0.00)”?

var numberFormat = new CultureInfo("en-US").NumberFormat;
numberFormat.CurrencySymbol = "€";
return numberFormat.GetCurrencyFormatString(); //this is an imaginary function that I need to return "'€'#,0.00;('€'#,0.00)"

我已经尝试根据每行的货币信息以编程方式设置货币符号。 据我所知,SSRS 不允许我使用表达式来设置货币符号。 它只提供一个下拉列表。

当我显示货币代码(例如 USD、CAD)时,我的用户不喜欢它,所以我坚持显示符号(例如 $、CA$)。

据我所知,您需要使用CultureInfo class 手动构造此格式字符串。

使用CurrencyPositivePatternCurrencyNegativePattern上的文档(参见此处此处),我整理了一些可行但可能需要一些调整的东西:

string GetCurrencyFormat(CultureInfo culture)
{            
    //we'll use string.Format later to replace {0} with the currency symbol
    //and {1} with the number format
    string[] negativePatternStrings = { "({0}{1})", "-{0}{1}", "{0}-{1}", "{0}{1}-", "({1}{0})",
                            "-{1}{0}", "{1}-{0}", "{1}{0}-", "-{1} {0}", "-{0} {1}",
                            "{1} {0}-", "{0} {1}-", "{0} -{1}", "{1}- {0}", "({0} {1})",
                            "({1} {0})" };
    string[] positivePatternStrings = { "{0}{1}", "{1}{0}", "{0} {1}", "{1}{0}" };

    var numberFormat = culture.NumberFormat;

    //Generate 0's to fill in the format after the decimal place
    var decimalPlaces = new string('0', numberFormat.CurrencyDecimalDigits);

    //concatenate the full number format, e.g. #,0.00
    var fullDigitFormat = $"#{numberFormat.CurrencyGroupSeparator}0{numberFormat.CurrencyDecimalSeparator}{decimalPlaces}";

    //use string.Format on the patterns to get the positive and 
    //negative formats
    var positiveFormat = string.Format(positivePatternStrings[numberFormat.CurrencyPositivePattern],  
                                       numberFormat.CurrencySymbol, fullDigitFormat);
    var negativeFormat = string.Format(negativePatternStrings[numberFormat.CurrencyNegativePattern], 
                                       numberFormat.CurrencySymbol, fullDigitFormat);

    //finally, return the full format
    return $"{positiveFormat};{negativeFormat}";
}

例如,这将返回$#,0.00;($#,0.00)用于en-US£#,0.00;-£#,0.00用于en-GB

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM