问题
Does anyone know why this Format command produces the following strange results:
textbox1.Text = String.Format("{0:+;-}{0,7:0.000;0.000}", dblVariable);
Here are the strange results (check the signs of the formatted text - the sign is incorrect for numbers smaller than 0.5):
dblVariable textbox1.Text
-0.100000 + 0.100
-0.200000 + 0.200
-0.300000 + 0.300
-0.400000 + 0.400
-0.500000 - 0.500
Thanks
回答1:
The article in MSDN describes the issue. Look at what is said next to Two sections:
If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, the resulting zero is formatted according to the first section.
In your case the format of the sign is {0:+;-}. This effectively means that there is no number format, just sign format. So when rounding to this format it must be rounded to a integer number. So in case of -0.1 to -0.4 the number is rounded to 0, which uses first section (+), but -0.5 is rounded to -1, so second section (-) is used.
You can fix it by only using single format:
textbox1.Text = String.Format("{0,7:+ 0.000;- 0.000}", dblVariable)
来源:https://stackoverflow.com/questions/28616396/issue-with-formatting-a-double-variable-to-show-in-textbox-in-c-sharp