Issue with Formatting a double variable to show in textbox in C#

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 14:14:08

问题


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

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