Try this:
void Main()
{
var d = decimal.Parse("2345000012999922");
Console.Out.WriteLine("{0:#### #### ## #### ##}", d);
}
First convert to decimal, then use your own strategy.
Formatting of numbers works right-to-left, meaning if you had 2 numbers as follows:
- 2345000012999922
- 23450000129999
And we did something like:
void Main()
{
var d1 = decimal.Parse("23450000129999");
var d2 = decimal.Parse("234500001299");
Console.Out.WriteLine("{0:#### #### ## #### ##}", d1);
Console.Out.WriteLine("{0:#### #### ## #### ##}", d2);
Console.Out.WriteLine("{0:0000 0000 00 0000 00}", d1);
Console.Out.WriteLine("{0:0000 0000 00 0000 00}", d2);
}
We'd get:
23 4500 00 1299 99
2345 00 0012 99
0023 4500 00 1299 99
0000 2345 00 0012 99
(Notice the 0-padding).
In a format string, "0" means put the corresponding digit here, if present, otherwise pad with a 0. A "#" means, put the corresponding digit here, if present, otherwise ignore it.
With this in mind, I think your best strategy would be something like:
void Main()
{
var s1 = "23450000129999";
var s2 = "234500001299";
var n1 = s1.Length;
var n2 = s2.Length;
var c = 12;
var f1 = "{0:#### #### ## #### ##}";
var f2 = "{0:#### #### ## ####}";
var d1 = decimal.Parse(s1);
var d2 = decimal.Parse(s2);
Console.Out.WriteLine(n1 > c ? f1 : f2, d1);
Console.Out.WriteLine(n2 > c ? f1 : f2, d2);
}
This will give:
23 4500 00 1299 99
23 4500 00 1299
The idea is that you check the string-length of the input string first. If it is 12, then you have the last optional bit absent, so you use the truncated format-string. If it is more than 12 (or equal to 14) then use the full format-string.
The other approaches such as regex and string manipulation are good approaches too, though I would suspect that they are less-performant. You should test all approaches though, especially if this piece of code will run many, many times (e.g., if you are showing data in a table).
You can improve the readability of the code further using extension methods by defining something like
public static class FormattingHelper
{
public static string GetFormatString(this string s)
{
if (s.Length == 12)
return "{0:#### #### ## ####}";
else
return "{0:#### #### ## #### ##}";
}
}
void Main()
{
var s1 = "23450000129999";
var s2 = "234500001299";
var d1 = decimal.Parse(s1);
var d2 = decimal.Parse(s2);
Console.Out.WriteLine(s1.GetFormatString(), d1);
Console.Out.WriteLine(s2.GetFormatString(), d2);
}