将数字格式设置为独立的int和decimal部分

本文关键字:int decimal 部分 独立 数字 格式 设置 | 更新日期: 2023-09-27 18:29:19

我正在尝试做一些与c#docs非常相似的事情,例如:

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

但是我非常想避免,除非没有其他方法

将数字格式设置为独立的int和decimal部分

可以定义自己的特殊货币格式,但。。。我不确定我是否会这么做。这有点像是对NumberFormatInfo对象的滥用:

EDIT:将值的数据类型从十进制更改为双

// 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美分)"

在.Net中使用复合格式无法实现正确的分离。您必须自己分离部分:

decimal value = 123.23m;
Console.WriteLine(
    @"{0:0} dollars and {1:#0} cents",
    Math.Truncate(value),                 // Dollars
    (value - Math.Truncate(value)) * 100m // Cents
);
// Output: 123 dollars and 23 cents

顺便说一句,你永远不应该使用floatdouble来存储钱,除非你想让IEEE-754取整模式偷走你的钱或导致你欠更多的钱。

编写一个程序,用户输入一个实数,如12.842,然后输出整数部分和小数部分,同时使用类型转换来执行所需的操作。输出看起来像:整数部分为:12小数部分为:842