【发布时间】:2015-07-18 05:51:24
【问题描述】:
我想我发现了一些仅靠格式化字符串无法完成的事情:我需要一个允许我格式化双精度以不显示小数的字符串,这样:
- 数字是千分隔的
- 0 显示破折号
- 括号内显示负数
- 0.5 舍入为 1,-0.5 舍入为 -1
- 0.4999.. 舍入为 0,-0.4999... 舍入为 -0(必须显示为“(0)”)
我已经到了。
"{0:#,0;(#,0);-}"
但是,这会将(-0.5 到 0.5)之间的数字显示为“-”。如果我将其替换为以下内容。
"{0:#,0.#;(#,0.#);-}"
这“没问题”,除了它会显示带小数点的数字,我需要将它们四舍五入。
出于说明目的,我尝试过:
string format = "#,0;(#,0);-";
Console.WriteLine(1000000.ToString(format));
Console.WriteLine(1000.ToString(format));
Console.WriteLine(100.ToString(format));
Console.WriteLine(10.ToString(format));
Console.WriteLine(1.ToString(format));
Console.WriteLine(0.5.ToString(format));
Console.WriteLine(0.4.ToString(format));
Console.WriteLine(0.ToString(format));
Console.WriteLine((-0.4).ToString(format));
Console.WriteLine((-0.5).ToString(format));
Console.WriteLine((-1).ToString(format));
Console.WriteLine((-1000000).ToString(format));
这给出了:
1,000,000
1,000
100
10
1
1
-
-
-
(1)
(1)
(1,000,000)
还有:
string format = "#,0.#;(#,0.#);-";
Console.WriteLine(1000000.ToString(format));
Console.WriteLine(1000.ToString(format));
Console.WriteLine(100.ToString(format));
Console.WriteLine(10.ToString(format));
Console.WriteLine(1.ToString(format));
Console.WriteLine(0.5.ToString(format));
Console.WriteLine(0.4.ToString(format));
Console.WriteLine(0.ToString(format));
Console.WriteLine((-0.4).ToString(format));
Console.WriteLine((-0.5).ToString(format));
Console.WriteLine((-1).ToString(format));
Console.WriteLine((-1000000).ToString(format));
哪些输出:
1,000,000
1,000
100
10
1
0.5
0.4
-
(0.4)
(0.5)
(1)
(1,000,000)
但这就是我想要实现的目标:
1,000,000
1,000
100
10
1
1
0
-
(0)
(1)
(1)
(1,000,000)
所以我决定使用第一个格式字符串,然后重新处理那些显示为“-”的值,但我想知道是否有办法单独使用格式字符串。
感谢您的帮助!
【问题讨论】:
-
你真正想要的输出是什么?
-
这是另一个想法。事先单独进行舍入,并使用更简单的字符串格式。显然,这不仅仅是格式字符串。
-
我已经明确了我现在想要完成的工作,谢谢@Greg。是的,ryanyuyu,我想到了这一点,但让 (0) 以这种方式出现,我取得了很大的成功。
-
"0 显示破折号" 什么是零?仅整数零?
-
嗨@weston,我已经澄清了我想要完成的工作,并且得到了我所期待的答案。还是谢谢。
标签: c# .net vb.net formatting string-formatting