views:

732

answers:

4

Greetings.

Imagine you've been given a string (from somewhere you can't control). In that string is a decimal number. You want to add commas (ie: turn 1234567.89 into 1,234,567.89) to that number while keeping the entire string intact. The currency symbol before the number will vary, but the comma-formatting doesn't have to vary by culture.

Is there an easy way to do this in .NET?

If there's not an easy way, I'll go into further detail as to what I had planned to do. We can use string.Substring() to get the number out because it is always between some static text. For example:

Our string:

string s1 = "Blah Blah Blah. Total price: $1234567.89; Blah Blah Blah Blah"

We can get at the price like this:

int start = s1.IndexOf("Total price: ") + 13;
int length = s1.IndexOf(";") - start;
string trim = s1.Substring(start, length);

Grab the currency character, leave the rest:

char curr = trim[0];
string sAmount = s1.Substring(1, s1.Length);

Now we can format our decimal:

decimal dAmount;
if (decimal.TryParse(sAmount, out dAmount))
{
   string formattedPrice = curr + dAmount.ToString("N2");
   Console.WriteLine(formattedPrice);
}

Now I could just insert the resulting string back into my original string where it should go. The point of writing this question is that this feels very nasty to me, and I was hoping to find a better way to deal with this.

Thanks for your time. I will be refreshing this for the next hour and will choose an answer within that time.

+1  A: 

The easy way is to use Regular Expression to find and replace.

Jim W
+2  A: 

Try something like this:

String.Format("Total Price: {0:C}", dAmount);

edit: sorry, too much coffee, read to fast. the above is the answer to how to insert commas/currency symbol into a number.

To answer the question about reinserting the new number into the old string, a regular expression would probably be best for identifying the number in the string, and for replacing it after you've done your formatting. I guess I'd need to see more examples of valid imput to help with the actual regex.

jenningj
+5  A: 
string input = "Blah Blah Blah. Total price: $1234567.89; Blah Blah Blah Blah";

string output = Regex.Replace(input, @"\d+(\.\d\d)?", match => decimal.Parse(match.Value).ToString("N"));
hjb417
Absolutely perfect. Thanks!
Joe Behymer
+2  A: 

You might want to look at the System.Globalization namespace.

You may trim the beginning and the trailing characters that are not numbers, then format your string according to your System.Globalization.CultureInfo.CurrentCulture.NumberFormat etc.

Will Marcouiller