c# format 如何显示正负号

飞客96004 2014-05-21 09:53:10
比如 int a = 1;
我想实现这样的功能 a.toString('xxxx") 得到的是 "+1";

我当然知道 "+" + 1 这样可以实现 我要的功能。
但是我想调用系统的toString 格式化format 去实现。
...全文
2858 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
IT凡人 2014-12-11
  • 打赏
  • 举报
回复
12楼正解,万分感谢。
save4me 2014-05-22
  • 打赏
  • 举报
回复 1
引用 8 楼 chenzhihuasilao 的回复:
楼上全是水经验的。楼主的意思是一个Int类型数据。toString(XXX) 返回的是"+1"或者"-1"这种带正负好的字符串。而XXX该怎么写。你们写个string.format()方法出来。。。。
不是这样吗: ToString("+#;-#;0"),正数前加+,负数前加-,0还是显示0。XXX = +#;-#;0
chenzhihuasilao 2014-05-22
  • 打赏
  • 举报
回复
楼上全是水经验的。楼主的意思是一个Int类型数据。toString(XXX) 返回的是"+1"或者"-1"这种带正负好的字符串。而XXX该怎么写。你们写个string.format()方法出来。。。。
chpst 2014-05-22
  • 打赏
  • 举报
回复
string str = "1"; str=string.Format("+{0}", str); this.label1.Text=str;
风之影子 2014-05-22
  • 打赏
  • 举报
回复
重写tostring()方法
excute 2014-05-22
  • 打赏
  • 举报
回复
4楼+1
SeeYou孙悟空 2014-05-22
  • 打赏
  • 举报
回复
不太明白你的意思。。。你要的是这样的效果吗?

string str = string.Format("{0}1",+);
string str = string.Format("{0}1",-);
exception92 2014-05-22
  • 打赏
  • 举报
回复

a.ToString("+0")
欢乐的小猪 2014-05-22
  • 打赏
  • 举报
回复
Console.WriteLine(i.ToString("+#;-#;0"));
save4me 2014-05-22
  • 打赏
  • 举报
回复
引用 10 楼 sunny906 的回复:
用扩展方法

public static class MyFormat
{
    public static string Format(this int n)
    {
        if (n > 0)
        {
            return string.Format("+{0}", n);
        }
        else if (n == 0)
        {
            return n.ToString();
        }
        else
        {
            return string.Format("-{0}", n);
        }
    }
}

//调用
            int i = 1;
            string s = i.Format();
            Console.WriteLine(s);
不用自己在扩展了,试一下是不是和你的效果完全一下:Console.WriteLine(i.ToString("+#;-#;0"));
sunny906 2014-05-22
  • 打赏
  • 举报
回复
用扩展方法

public static class MyFormat
{
    public static string Format(this int n)
    {
        if (n > 0)
        {
            return string.Format("+{0}", n);
        }
        else if (n == 0)
        {
            return n.ToString();
        }
        else
        {
            return string.Format("-{0}", n);
        }
    }
}

//调用
            int i = 1;
            string s = i.Format();
            Console.WriteLine(s);
devmiao 2014-05-21
  • 打赏
  • 举报
回复
http://stackoverflow.com/questions/5301201/how-to-force-a-sign-when-formatting-an-int-in-c-sharp
save4me 2014-05-21
  • 打赏
  • 举报
回复

			int i = 0;
			Console.WriteLine(i.ToString("+#;-#;0"));

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧