格式化数据的输出方法

          平时我们使用的是Console类提供的格式化数据输出方法。那么,C#中有没有别的方法可以使用呢?答案是肯定的,用String类的格式化方法也可以有同样的功能。String类提供了很强大的Format()方法用以格式化字符串,它的语法和WriteLine()类似。

Format()的语法如下:

        string str=string.Format("格式化字符串",参数列表);

举个简单的例子:

       string str=string.Format("{0}+{1}={2}",1,2,1+2);

       Console.WriteLine(str);

输出结果:

       1+2=3

其中,”{0}+{1}={2}“就是格式字符串,{0},{1},{2}为占位符。

除了上面的用法之外,string.Format()方法还有格式化数值的功能,具体用法如表所示:

格式化数值
字符 说明 示例 输出
C 货币 string.Format("{0:C3}",2) $ 2.000
D 十进制 string.Format("{0:D3}",2) 002
E 科学计数法 1.20E+001 1.20E+001
G 常规 string.Format("{0:G}",2) 2
N 用逗号隔开的数字 string.Format("{0:N}",25000) 25,000.00
X 十六进制 string.Format("{0:X000}",12) C
P 百分比 string.Format("{0:P}",12.34) 1234.00%

举例说明:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FormatTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Empty;
            Console.WriteLine("标准数字化格式");
            str = string.Format(
                "(C)Currency:{0:C}
"+
                "(D)Decimal:{0:D}
" +
                "(G)General:{1:G}
" +
                "(p)Percent:{1:P}
" +
                "(X)Hexadecimal:{0:X}
" ,
                -12345,-123.4567f);
            Console.WriteLine(str);
            Console.ReadLine();
        }
        
    }
}

代码说明:

       代码中,{0,C},{1,P}中的0、1就是占位符,C、P代表不同的数据类型。

运行结果:



        

原文地址:https://www.cnblogs.com/dyllove98/p/3217822.html