格式化数据的输出方法

          平时我们使用的是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+0011.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}\n"+
                "(D)Decimal:{0:D}\n" +
                "(G)General:{1:G}\n" +
                "(p)Percent:{1:P}\n" +
                "(X)Hexadecimal:{0:X}\n" ,
                -12345,-123.4567f);
            Console.WriteLine(str);
            Console.ReadLine();
        }
        
    }
}

代码说明:

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

运行结果:



        

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值