我正在尝试做与this c# docs example非常相似的事情:

int value = 123;
Console.WriteLine(value.ToString(@"\#\#\# ##0 dollars and \0\0 cents \#\#\#"));
// Displays ### 123 dollars and 00 cents ###


除了我希望它实际使用小数:

double value = 123.095;
Console.WriteLine(value.ToString(@"\#\#\# ##0 dollars and 0000 \#\#\#"));
// Should display ### 123 dollars and 0950 ###, but it doesn't (of course)


尝试过:

Console.WriteLine(value.ToString(@"\#\#\# ##0. dollars and 0000 cents \#\#\#"));


但是打印(当然)十进制分隔符,这是我不想要的。
我知道我可以做这样的事情:

String.Format("{0:##0} {1:0000}", 123, 123);


但是非常希望避免,除非没有其他方法

最佳答案

您可以定义自己的特殊货币格式,但是...我不确定是否会这样做。似乎是对NumberFormatInfo对象的滥用:

编辑:将值的数据类型从十进制更改为双精度

// works with either decimal or double
double value = 123.095;

var mySpecialCurrencyFormat = new System.Globalization.NumberFormatInfo();

mySpecialCurrencyFormat.CurrencyPositivePattern = 3;
mySpecialCurrencyFormat.CurrencyNegativePattern = 8;
mySpecialCurrencyFormat.NegativeSign = "-";
mySpecialCurrencyFormat.CurrencySymbol = "cents";
mySpecialCurrencyFormat.CurrencyDecimalDigits = 4;
mySpecialCurrencyFormat.CurrencyDecimalSeparator = " dollars and ";
mySpecialCurrencyFormat.CurrencyGroupSeparator = ",";
mySpecialCurrencyFormat.CurrencyGroupSizes = new[] { 3 };


Console.WriteLine(value.ToString("C", mySpecialCurrencyFormat));


输出为“ 123美元和0950美分”

编辑:使用CurrencyNegativePattern 15而不是8可能更有意义,因此,负值会导致整个字符串被括号括起来,这可能比仅在美元前面加上负号更容易混淆。例如,使用CurrencyNegativePattern = 15会使-123.095输出为“(123美元和0950美分)”

关于c# - C#中的数字格式-将整数和小数部分分开,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9926231/

10-15 14:16