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.