C#的字符串货币格式可以选择最多6个十进制数字吗? [英] Can C#'s string currency format optionally up to 6 decimal numbers?
问题描述
通过快速测试,C#的货币格式似乎不支持可选的小数位.
With a quick test C#'s currency format doesn't appear to support optional decimal places.
CultureInfo ci = new CultureInfo("en-US");
String.Format(ci, "{0:C2}", number); // Always 2 decimals
String.Format(ci, "{0:C6}", number); // Always 6 decimals
尝试自定义它不起作用.
Trying to customize it doesn't work.
String.Format(ci, "{0:C0.00####}", number); // two decimals always, 4 optional
是否可以使用带有可选小数位数的货币格式?
Is it possible to use the currency format with an optional number of decimals?
例如像这样显示$ 199.99或$ 0.009999或$ 5.00.
e.g. $199.99 or $0.009999 or $5.00 are shown like this.
推荐答案
有点麻烦,但是您可以先计算小数位数.然后,您可以使用该数字形成格式字符串.
It's a bit long-winded, but you could first calculate the number of decimal places. Then, you can use that number to form your format string.
您将需要此实用程序功能(贷记给一个名叫Joe的家伙):
You'll need this utility function (credits go to a guy by the name of Joe):
private int CountDecimalPlaces(decimal value)
{
value = decimal.Parse(value.ToString().TrimEnd('0'));
return BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
}
然后您可以按照以下步骤进行操作:
Then you can do something along these lines:
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);
这篇关于C#的字符串货币格式可以选择最多6个十进制数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!