views:

208

answers:

2

I have found on SO some posts, regarding formatting strings, representing numbers, to have digit group separators, during converting decimals (or other number data types) to string:

http://stackoverflow.com/questions/2100472/how-to-format-1700-to-1700-and-1000000-to-1000000-in-c

http://stackoverflow.com/questions/1142994/c-formating-price-value-string

What if I have these numbers already in string format (have read from a .txt file by StreamReader), but want to have group separators nevertheless (and in string format)?

Is parsing it to decimal and then back to string with needed formatting the most reasonable way in this case?

+1  A: 

Is parsing it to decimal and then back to string with needed formatting the most reasonable way

Yes. It will be less messy than doing this with string operations.

Henk Holterman
+1  A: 

Just out of curiosity I put this method together to see what it would take to add the separators to the string without parsing and formatting:

public static string AddGroupSeparators(string number) {
  int[] sizes = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes;
  int pos = number.LastIndexOf(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
  if (pos == -1) pos = number.Length;
  int sizeIndex = 0;
  while (sizes[sizeIndex] > 0 && pos > sizes[sizeIndex]) {
    pos -= sizes[sizeIndex];
    number = number.Insert(pos, CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator);
    if (sizeIndex < sizes.Length - 1) sizeIndex++;
  }
  return number;
}
Guffa
Thanks for a great example of string manipulation. (and making things even more evident) +1
rem