ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C#格式化处理字符串123456为"123,456"

C#格式化处理字符串123456为"123,456"

原创 Linux操作系统 作者:chenjq2010 时间:2011-03-05 14:14:11 0 删除 编辑
c# 字符串格式化处理之一: 
 [STAThread]
        static void Main(string[] args)
        {
            long a = 123456;
            int j = a.ToString().Length;
            string b = null;
            string c = null;
            if(a.ToString().Length>3)
            {
                if(j%3 == 0)
                {
                    for(int i = 0;i                    {
                        b += a.ToString().Substring(i*3,3) + ",";
                    }
                    if(b.Substring(b.Length-1) == ",")
                    {
                        c = b.Substring(0,b.Length-1);
                    }
                }
                else if((j-1)%3 == 0)
                {
                    for(int i = 0;i<(j-1)/3;i++)
                    {
                        b += a.ToString().Substring(i*3+1,3) + ",";
                    }
                    if(b.Substring(b.Length-1) == ",")
                    {
                        c = a.ToString().Substring(0,1) + "," + b.Substring(0,b.Length-1);
                    }
                }
                else if((j-2)%3 == 0)
                {
                    for(int i = 0;i<(j-1)/3;i++)
                    {
                        b += a.ToString().Substring(i*3+2,3) + ",";
                    }
                    if(b.Substring(b.Length-1) == ",")
                    {
                        c = a.ToString().Substring(0,2) + "," + b.Substring(0,b.Length-1);
                    }
                }
            }
            else if(a.ToString().Length <= 3)
            {
                c = a.ToString();
            }
            Console.WriteLine(c);
            Console.Read();
        }

另外,这里有一个非常简单的方法:
       [STAThread]
        static void Main(string[] args)
        {
               int a = 123456;
               string b = a.ToString("n");
                Console.WriteLine(b);
                Console.Read();
        }
输出的结果是:  123,456.00
如果要把后边的 “.00”去掉,只需要写:
        [STAThread]
        static void Main(string[] args)
        {
               int a = 123456;
               string b = a.ToString("n");
               string c = b.SubString(0,b.Length-3);
                Console.WriteLine(c);
                Console.Read();
        }
就over了。
    
 

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25253744/viewspace-688477/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2011-01-20

  • 博文量
    11
  • 访问量
    22796