经过快速测试,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 显示如下。
有点啰嗦,不过你可以先计算一下小数位数。然后,您可以使用该数字来形成格式字符串。
你需要这个实用函数(感谢一个名叫 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)