最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中格式化输出int整型变量为固定宽度前加0的形式,即printf中%02d之类的形式

C# crifan 7631浏览 0评论

【问题】

C#中,有个变量,为int型的4,想要格式化输出为04,相当于普通C语言中的printf中的%02d。

【解决过程】

1.已经找到之前的关于C#中的类似于printf中的用法了:

【记录】C#学习心得

string spritfTestStr = String.Format("Test sprintf in C#, number={0:D}, string=\"{1:s}\", float={2:0.000}", 100, "crifan", Math.PI);
//spritfTestStr = Test sprintf in C#, number=100, string="crifan", float=3.142

但是,此处尝试着写了多种方式:

{0:2D}

{0:02D}

{0:02d}

竟然都还是无法正常输出我要的%02d的效果。

2.后来好不容易从:String.Format Method (String, Object[]),中的:Custom Numeric Format Strings,找到了一些解释:

Format specifier

Name

Description

0

Zero placeholder

If the value being formatted has a digit in the position where the ‘0’ appears in the format string, then that digit is copied to the result string. The position of the leftmost ‘0’ before the decimal point and the rightmost ‘0’ after the decimal point determines the range of digits that are always present in the result string.

The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.

然后自己折腾,试了试:

{0:00}

才终于可以实现printf中的%02d的效果的。

代码为:

int intVal = 4;
string outputStr = String.Format("{0:00}", intVal); // -> 04

【总结】

总的来说,我感觉,C#在这部分细节的支持方面,虽然算是功能很强大,但是也蛮变态的。

竟然连一个普通的格式化,都搞得和别人如此不一样,搞得连个%02d都费了半天劲才找到具体用法。

真够坑爹的说。

转载请注明:在路上 » 【已解决】C#中格式化输出int整型变量为固定宽度前加0的形式,即printf中%02d之类的形式

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (4)

  1. ……直接变量x.toString("00"); 即可转为固定长度序列的数字。 只能说楼主走了好多弯路,不送。
    渣渣8年前 (2016-11-16)回复
  2. 那在Windows应用程序中呢
    天使10年前 (2014-10-06)回复
    • 找到啦,是string.format("{0,4}",num);
      天使10年前 (2014-10-06)回复
  3. 变量.tostring("02D");
    asdfas12年前 (2012-11-20)回复
87 queries in 0.176 seconds, using 22.09MB memory