Format number with leading zeros and thousands separator

I would like to format an integer so that it has leading zeros and thousands of separators at the same time.

I know it someInt.ToString("D6");

will give me leading zeros, but apparently it doesn't allow it NumberGroupSeparator

. On the other hand someInt.ToString("N");

will give me delimiters but no leading zeros ...

Can both be combined for printing 123456

like 00 123 456

? I know I can get the string created with N

and then manually add zeros to the string in a loop or something, but maybe better?

EDIT: The number of zeros (full digit of digits) should be adjustable.

+3


source to share


4 answers


If you want 00 123 456, just do:

123456.ToString("00 000 000")

      



If you want a fixed sum of zero, all I can think of is:

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

      

+2


source


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 if this works or not.



Corrected and 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));

      

+2


source


Something like that

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

      

0


source


You are trying to use standard format strings to achieve what you want, however you need to look at Custom Digital String Format (MSDN) . They should allow you to set things up exactly as you need them.

0


source







All Articles