简体   繁体   中英

Adding commas to a decimal number which is in a string of text with .NET 2.0

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 , 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.

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"));

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.

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.

简单的方法是使用正则表达式来查找和替换。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM