简体   繁体   English

带前导零和千位分隔符的格式编号

[英]Format number with leading zeros and thousand separator

I'd like to format an integer in a way that it has leading zeros and thousand separators at the same time. 我想以一种同时具有前导零千位分隔符的方式格式化整数。

I know that someInt.ToString("D6"); 我知道someInt.ToString("D6"); will give me leading zeros, but apparently it doesn't allow NumberGroupSeparator . 会给我前导零,但显然它不允许NumberGroupSeparator On the other hand someInt.ToString("N"); 另一方面someInt.ToString("N"); will give me separators but no leading zeros... 会给我分隔符,但没有前导零...

Is it possible to combine both to print 123456 as 00 123 456 ? 是否可以将两者结合起来打印123456作为00 123 456 I know I can get string created with N and then manually add zeros to string in a loop or something, but maybe there's better way? 我知道我可以用N创建字符串,然后在循环或其他东西中手动将零添加到字符串,但也许有更好的方法?

EDIT: Number of padding zeros (total digits length of number) should be adjustable. 编辑:填充零的数量(数字的总长度)应该是可调整的。

If you want 00 123 456, just do: 如果你想要00 123 456,那就做:

123456.ToString("00 000 000")

If you need a fixed amount of zero's, all I can think of is this: 如果您需要固定数量的零,我能想到的就是:

int NUM_LENGTH = 6;

//This is not very elegant
var NUM_STR = String.Join("", Enumerable.Range(0, NUM_LENGTH).Select((x, i) => (NUM_LENGTH - i) % 3 == 0 ? " 0" : "0"));

//But at least it works:
var example1 = 123456.ToString(NUM_STR); //Outputs  123 456
var example2 = 1234.ToString(NUM_STR); //Outputs 001 234

I think the following should work. 我认为以下内容应该有效。

int value = 102145;
int num_length = 10; // it may change as you expected
string format = "000,000,000,000,000";
string tmp = value.ToString(format);
Console.Out.WriteLine(tmp.Substring(tmp.Length - num_length - tmp.Length/4 + 1 ));

Please let me know whether it works or not. 请告诉我它是否有效。

Corrected & working version: 更正和工作版本:

int value = 102145;
int num_length = 12;
string format = "000,000,000,000,000,000";
string tmp = value.ToString(format);
int totalLength = format.Replace("000,", "000").Length;
int rem = (totalLength - num_length ) / 3;
Console.Out.WriteLine(tmp.Substring(totalLength - num_length + rem));

像这样的东西

 .toString("#,###");

You're trying to use the Standard format strings to acheive what you're after, however you're going to need to look at the Custom Numeric Format Strings (MSDN) . 您正在尝试使用标准格式字符串来实现您所追求的内容,但是您需要查看自定义数字格式字符串(MSDN) These should enable to set things up exactly as you require. 这些应该能够完全按照您的要求进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM