Can C#和#x27;s字符串货币格式(可选)最多6个十进制数字?

Can C#和#x27;s字符串货币格式(可选)最多6个十进制数字?,c#,localization,C#,Localization,通过快速测试,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 d

通过快速测试,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
是否可以使用具有可选小数位数的货币格式


e、 g.$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的人):

然后你可以按照以下思路做一些事情:

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);

我可以建议您编写一个方法,该方法将首先获取最大位数的字符串,然后在返回结果之前删除可选值(如果为零)。谢谢,主要问题是您无法根据区域性自动设置货币格式(因为您手动写入输出)。在某些语言中,199.99美元写为199,99美元。这个示例可以在某些区域性或情况下工作,但在这种情况下不行,因为它总是输出“$”然后输出格式化的数字。我必须使用字符串格式(“0.#######”)添加一个Decimal.TryParse值,以首先去掉CountDecimalPlaces中多余的0,否则,它会计算出0.10万美元,而不删除超过2位小数的多余数字。如果你加上这一点,我将把它标记为答案。(否则它们就不是真正可选的,多亏了您和
Sinatr
组合工作得很好)是的,(最小小数点是2,如果需要,可以轻松设置最大值),其余代码工作得很好。我没有测试这种情况,但现在我很惊讶实用程序函数也计算了尾随的零。我会看看是否有其他方法。我认为这很好,它只需要
Decimal.TryParse(amount.Value.ToString(“0.”Decimal.GetBits(removeTrailingZerosAmount)[3])(最大十进制所需的哈希数)out removeTrailingZerosAmount)
然后
count=BitConverter.GetBytes(Decimal.GetBits(removeTrailingZerosAmount)[3])[2]如果解析成功。当然,如果有更好的方法我感兴趣的话,但是这也可以完成工作。@Iko似乎没有一种方法可以在不转换为字符串的情况下丢弃尾随的零。请参阅我的最新答案。
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);