How to apply different formatting depending on whether number is positive or negative

心已入冬 提交于 2019-12-10 18:19:06

问题


I'm outputting a Double that can be either (+) or negative (-). If the number is a negative the symbol (-) is included automatically, is there a way to do this for positive numbers as well?

The only (horrible) way I can do this is :

If MyNumber <= 0 then
    string.Format("{0:0.00}", MyNumber)
Else
    string.Format("+{0:0.00}", MyNumber)
End If 

回答1:


You can use the section separator in your format:

string.Format("{0:+0.00;-0.00}", num);

The format before the semi-colon will be used for positive numbers. The format after will be used for negative numbers. If you want a separate format for zero, add another format after the negative number format:

string.Format("{0:+0.00;-0.00;0.00}", num);



回答2:


string.Format("{0:+0.00;-0.00;0.00}”,MyNunber);


来源:https://stackoverflow.com/questions/7193917/how-to-apply-different-formatting-depending-on-whether-number-is-positive-or-neg

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