How to deal with leading zeros when formatting an int value

Viewed 391

have a bit of a blank. If I want to apply the following format (## ### ###) to an int value I would do this.

string myFormat = "## ### ###";
int myPin = 18146145;
Console.WriteLine(myPin.ToString(myFormat)); //18 146 145

Issue however is with the values of say "02112321" to be formatted as "02 112 321" applying this exact formatting "## ### ###". the 0 in this case would fall away.

2 Answers

Formatting consists of converting a value to a string by giving it a certain shape. Therefore, formatting does not apply to strings (because they are already strings). You can convert the string to a number and then convert it back to string and apply the desired format.

string myFormat = "00 000 000";
string s = "02112321";
string formatted = Int32.Parse(s).ToString(myFormat); // ==> "02 112 321"

If you need leading zeroes, use the format string "00 000 000" instead of "## ### ###".

Note that Int32.MaxValue is 2,147,483,647. If you need to format lager numbers, use Int64.Parse allowing numbers up to 9,223,372,036,854,775,807.

You can use the 0 as format specifier. From the documentation :

Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

You can do like :

02112321.ToString("00 000 000", CultureInfo.InvariantCulture)

Edit: As indicate by @olivier-jacot-descombes, I miss a point. The OP want format a integer from a string to a string. Example "02112321" to "02 112 321".

It's possible with a intermediate conversion, string to int to string. With the example, this done "02112321" to 02112321 to "02 112 321" :

var original = "02112321";
var toInt = int.Parse(original, CultureInfo.InvariantCulture);
var formated = toInt.ToString("00 000 000", CultureInfo.InvariantCulture)
Related