如何应用不同的格式,取决于数字是正数还是负数 [英] How to apply different formatting depending on whether number is positive or negative

查看:153
本文介绍了如何应用不同的格式,取决于数字是正数还是负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我输出一个可以是(+)或负( - )的 Double 。如果数字是负数,则会自动包含符号( - ),有没有办法为正数做这个?

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 


推荐答案

您可以使用格式分隔符:

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

这篇关于如何应用不同的格式,取决于数字是正数还是负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆