问题的StringFormat的小负数已四舍五入负数、四舍五入、问题、StringFormat

2023-09-03 17:39:53 作者:与往事干杯

我试图写一个字符串格式,将圆形或垫数字到小数点后两位,也显示负数用括号括起。这是一个在WPF应用程序,但它适用于任何.NET的StringFormat用例。例如:

I am trying to write a string format that will round or pad numbers to two decimal places, and also display negative numbers with brackets around them. This is in a in a WPF application, but it applies to any .net StringFormat use case. For example:

2.0 - > 2.00 在-2.0 - >(2.00) 0.01 - > 0.01 -0.01 - >(0.01) 0.001 - > 0.00 -0.001 - >(0.00)

最后一个,舍入为零一个非常小的负数,就是问题所在。我还是想括号,以表明它是消极的。

The last one, a very small negative number rounded to zero, is the problem. I still want the brackets to indicate that it was negative.

我的第一个版本是一个字符串格式如下:

My first version was a string format as follows:

{0:#,##0.00 ;(#,##0.00)}

这是不行的,因为这将数字四舍五入应用交换机正/负,从而推定了0.00不为负了。

This doesn't work, because it rounds the number before applying the switch on positive/negative, thus deeming that the 0.00 is not negative.

那么我想这一点,在支架上的逻辑分隔成自己的格式块,前后数后:

I then tried this, to separate the bracket logic into its own formatting blocks, before and after the number:

{0:;(}{0:#,##0.00 ;#,##0.00}{0:;)}

奇怪的是,然而,这表现出相同的行为与原始的例子。它的工作原理正确的-0.01,但仍不会显示括号内为-0.001。不知怎的,第一个和最后的标记必须在中间的数字显示令牌的舍入行为的回升。

Bizarrely, however, this exhibits identical behaviour to the original example. It works correctly for -0.01, but still does not display brackets for -0.001. Somehow the first and last tokens must be picking up on the rounding behaviour of the numerical display token in the middle.

有没有人对如何格式化这个所以它的工作原理我想怎么想法?

Does anyone have ideas on how to format this so it works how I want?

推荐答案

当你说;(#,## 0.00) {0 :;(} 的值已经被四舍五入为0。因此,它不会让你你期待的结果。

When you say ;(#,##0.00) or {0:;(}. The value gets already rounded off to 0. Hence it does not get you the result you are expecting.

因此​​,最好是检查就签收前是负的。

So it is better to check the sign before it is negative.

var value = -0.001M;
string decimalFormat = value > 0 ? "{0:#,##0.00}" : "({0:#,##0.00})";
Console.WriteLine(String.Format(decimalFormat, value));

根据标志应该做的字符串格式之间进行选择。

Choosing between the string format based on the sign should do.