Issue with StringFormat for small negative numbers that have been rounded

拜拜、爱过 提交于 2020-01-13 19:05:48

问题


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

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/19586067/issue-with-stringformat-for-small-negative-numbers-that-have-been-rounded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!