格式化数字

本文深入探讨了C#中数值格式化和日期格式化的方法,包括货币格式、十进制格式、指数格式等,并展示了如何在代码中实现这些格式化操作。同时,介绍了日期和时间的格式化方法,如短日期、长日期、全日期和时间等模式,提供了实用的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字母 含义
C或c Currency 货币格式
D或d Decimal 十进制格式(十进制整数,不要和.Net的Decimal数据类型混淆了)
E或e Exponent 指数格式
F或f Fixed point 固定精度格式
G或g General 常用格式
N或n 用逗号分割千位的数字,比如1234将会被变成1,234
P或p Percentage 百分符号格式
R或r Round-trip 圆整(只用于浮点数)保证一个数字被转化成字符串以后可以再被转回成同样的数字
X或x Hex 16进制格式

public class FormatSpecApp
{
public static void Main(string[] args)
{
int i = 123456;
Console.WriteLine("{0:C}", i); // ¥123,456.00
Console.WriteLine("{0:D}", i); // 123456
Console.WriteLine("{0:E}", i); // 1.234560E+005
Console.WriteLine("{0:F}", i); // 123456.00
Console.WriteLine("{0:G}", i); // 123456
Console.WriteLine("{0:N}", i); // 123,456.00
Console.WriteLine("{0:P}", i); // 12,345,600.00 %
Console.WriteLine("{0:X}", i); // 1E240
}
}
精度控制标识控制了有效数字的个数或者十进制数小数的位数。

Console.WriteLine("{0:C5}", i); // ¥123,456.00
Console.WriteLine("{0:D5}", i); // 123456
Console.WriteLine("{0:E5}", i); // 1.23456E+005
Console.WriteLine("{0:F5}", i); // 123456.00000
Console.WriteLine("{0:G5}", i); // 1.23456E5
Console.WriteLine("{0:N5}", i); // 123,456.00000
Console.WriteLine("{0:P5}", i); // 12,345,600.00000 %
Console.WriteLine("{0:X5}", i); // 1E240

字符串和日期

D MM/dd/yyyy ShortDatePattern(短日期模式)
D dddd,MMMM dd,yyyy LongDatePattern(长日期模式)
F dddd,MMMM dd,yyyy HH:mm Full date and time (long date and short time)(全日期和时间模式)
F dddd,MMMM dd,yyyy HH:mm:ss FullDateTimePattern (long date and long time)(长日期和长时间)
G MM/dd/yyyy HH:mm General (short date and short time)(通用模式,短日期和短时间)
G MM/dd/yyyy HH:mm:ss General (short date and long time)(通用模式,短日期和长时间)
M,M MMMM dd MonthDayPattern(月天模式)
r,R ddd,dd MMM yyyy,HH':'mm':'ss 'GMT' RFC1123Pattern (RFC1123模式)
S yyyy-MM-dd HH:mm:ss SortableDateTimePattern (conforms to ISO 8601) using local time(使用本地时间的可排序模式)
T HH:mm ShortTimePattern (短时间模式)
T HH:mm:ss LongTimePattern(长时间模式)
U yyyy-MM-dd HH:mm:ss UniversalSortable-DateTimePattern (conforms to ISO 8601) using universal time(通用可排序模式)
U dddd,MMMM dd,yyyy,HH:mm:ss UniversalSortable-DateTimePattern(通用可排序模式)
y,Y MMMM,yyyy YearMonthPattern(年月模式)

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("f"));//2012年5月12日 15:42
Console.WriteLine(dt.ToString("d"));2012/5/12 ==dt.ToShortDateString()
Console.WriteLine(dt.ToString("g"));2012/5/12 15:42
Console.WriteLine(dt.ToString("m"));//5月12日
Console.WriteLine(dt.ToString("r"));Sat,12, May 2012 15:47:55 GMT
Console.WriteLine(dt.ToString("s"));2012-05-12T15:49:09

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值