How to format int to string with leading Zeros and Commas

I need to convert an int to a string that always contains 9 digits + 2 commas.

1 will become 000 000 001

12345 will become 000,012,345

etc.

I know I can use ToString (). PadLeft (...) to add leading zeros, but don't know how to add commas without using a few tests. Is there a more efficient way to do this?

+4
source share
5 answers

Just using:

int myint = 12345; string formatted = myint.ToString("000,000,000"); 
+10
source
 int number = 12345; String result = String.Format("{0:000,000,000}", number); 

a source

+5
source

You can use a custom string format that would be simple, but probably not as effective as the version-specific manual format:

 string text = value.ToString("000,000,000", CultureInfo.InvariantCulture); 

Note the use of CultureInfo.InvariantCulture to avoid using the group symbol of the current culture (and number).

One option for manual rolling:

 static string ToDigitsAndCommas(int value) { char[] chars = new char[11]; chars[3] = ','; chars[7] = ','; int remainder; for (int i = 0; i < 9; i++) { value = Math.DivRem(value, 10, out remainder); chars[10 - i - (i / 3)] = (char) (remainder + '0'); } return new string(chars); } 

I would recommend a comparative analysis of this to find out if it is really needed, and not a simple code :)

+3
source

Just use the format specifier in ToString() :

 var stringified = yourNumber.ToString("000,000,000"); 

And you get back the null commas w.

+2
source

Use ToString () and specify the resulting format as an argument.

See MSDN for more information.

+1
source

Source: https://habr.com/ru/post/1439857/


All Articles