C#字符串格式化

本文介绍了C#中数值(如货币、科学计数法、分割数字等)和日期(日期时间对象的多种格式化方法)的格式化技巧,包括`ToString`和`string.Format`函数的使用实例。

数值规范

也可写成int money = 368; money .ToString("C");

string.Format("金额:{0:C}", 368);                                => ¥368.00
string.Format("科学计数法:{0:C}", 12000.1);              => 1.200001E+005
string.Format("分割数字:,{0:E0}", 123456789);       => 123,456,789
string.Format("π取两位小数:{0:F2}", Math.PI);           => 3.14
string.Format("16进制:{0:X4}", 33);                             => 0021
string.Format("百分比:{0:P0}", 0.99);                          => 99%

日期格式化

DateTime strDate = DateTime.Now;   

也可写成strDate.ToString("Y");
string.Format("短日期格式:{0:d}", strDate);       =>短日期格式:2024/4/29
string.Format("长日期格式:{0:D}", strDate);       =>长日期格式:2024年4月29日
string.Format("完整日期格式:{0:f}", strDate);    =>完整日期格式:2024年4月29日 16:26
string.Format("短时间格式:{0:t}", strDate);        =>短时间格式:16:26
string.Format("长时间格式:{0:T}", strDate);       =>长时间格式:16:26:54
string.Format("月日格式:{0:M}", strDate);          =>月日格式:4月29日
string.Format("年月格式:{0:y}", strDate);            =>年月格式:2024年4月

           

      

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值