簡體   English   中英

C#的字符串貨幣格式可以選擇最多6個十進制數字嗎?

[英]Can C#'s string currency format optionally up to 6 decimal numbers?

通過快速測試,C#的貨幣格式似乎不支持可選的小數位。

CultureInfo ci = new CultureInfo("en-US");
String.Format(ci, "{0:C2}", number); // Always 2 decimals
String.Format(ci, "{0:C6}", number); // Always 6 decimals

嘗試自定義它不起作用。

String.Format(ci, "{0:C0.00####}", number); // two decimals always, 4 optional

是否可以使用帶有可選小數位數的貨幣格式?

例如$ 199.99或$ 0.009999或$ 5.00就像這樣顯示。

我不確定使用C是否有直接的方法,但您可以這樣做:

decimal number = 1M;
CultureInfo ci = new CultureInfo("en-US");
string formattedValue = string.Format("{0}{1}", 
                                    ci.NumberFormat.CurrencySymbol, 
                                    number.ToString("0.00####")); 

這有點啰嗦,但你可以先計算小數位數。 然后,您可以使用該數字來形成格式字符串。

你需要這個實用程序功能(獎勵給Joe的名字):

private int CountDecimalPlaces(decimal value)
{
    value = decimal.Parse(value.ToString().TrimEnd('0'));
    return BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
}

然后你可以沿着這些方向做點什么:

decimal number = 5.0M;

CultureInfo ci = CultureInfo.CurrentCulture;

NumberFormatInfo nfi = ci.NumberFormat.Clone() as NumberFormatInfo;

// Count the decimal places, but default to at least 2 decimals
nfi.CurrencyDecimalDigits = Math.Max(2 , CountDecimalPlaces(number));

// Apply the format string with the specified number format info
string displayString = string.Format(nfi, "{0:c}", number);

// Ta-da
Console.WriteLine(displayString);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM