簡體   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