String.Format的用法

本文详细介绍C#中使用string.Format方法进行各种类型的数据格式化操作,包括数字、货币、百分比、日期等常见格式的处理技巧。

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


1.字符串数字的格式化

 string str1 =string.Format("{0:N1}",12345);             //result: 12,345.0
 string str2 =string.Format("{0:N2}",12345);             //result: 12,345.00
 string str3 =string.Format("{0:N3}",12345);             //result: 12,345.000
 string str8 =string.Format("{0:F1}",12345);             //result: 12345.0
 string str9 =string.Format("{0:F2}",12345);             //result: 12345.00
 string str11 =(12345/100.0).ToString("#.##");           //result: 123.45
 string str12 =(12345/100).ToString("#.##");             //result: 123


2.货币的格式化

<span style="font-family:SimSun;">string.Format("{0:C}",20)        //结果为¥20</span>
<pre name="code" class="sql"><span style="font-family:SimSun;">string.Format("{0:C1}",20.12)    //结果为¥20.1</span>



3.用分号隔开的数字,并指定小数点后的位数

string.Format("{0:N}", 14200)        //结果为:14,200.00 (默认为小数点后面两位)
string.Format("{0:N3}", 14200.2458)  //结果为:14,200.246 (自动四舍五入)


4.百分比的格式化

string.Format("{0:P}", 0.24583)     //结果为:24.58% (默认保留百分的两位小数)
string.Format("{0:P1}", 0.24583)    //结果为:24.6% (自动四舍五入)


5.日期的格式化

string.Format("{0:d}",System.DateTime.Now) //结果为:2009-3-20 (月份位置不是03)
string.Format("{0:D}",System.DateTime.Now) //结果为:2009年3月20日
string.Format("{0:f}",System.DateTime.Now) //结果为:2009年3月20日 15:37
string.Format("{0:F}",System.DateTime.Now) //结果为:2009年3月20日 15:37:52
string.Format("{0:g}",System.DateTime.Now) //结果为:2009-3-20 15:38
string.Format("{0:G}",System.DateTime.Now) //结果为:2009-3-20 15:39:27
string.Format("{0:m}",System.DateTime.Now) //结果为:3月20日
string.Format("{0:t}",System.DateTime.Now) //结果为:15:41
string.Format("{0:T}",System.DateTime.Now) //结果为:15:41:50





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值