Replace dot (.) With comma (,) with RegEx?

I am working on a C # application. I want to change the numeric number with a semicolon (,), where I have a period (.), Using a regex.

For example:

Price= 100,00.56 

As this international rule for representing numeric values, but in Sweden they have different ways for numbers. Like

 Price= 100.00,56 

So, I want to change the dot (.) To a comma (,) and the comma (,) to a dot (.) Using RegEx. Could help me with this.

+7
c # regex decimal-point cultureinfo
source share
6 answers

When formatting, you should use the string format overload , which accepts CultureInfo . The name of the culture for the Swedish language is "sv-SE", as can be seen here .

 decimal value = -16325.62m; Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("sv-SE"))); 

Edit

As @OregonGhost points out, parsing numbers should also be done using CultureInfo .

+23
source share

Also look

 System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator 
+5
source share

You can do this even without regular expression. for example

 var temp = price.Replace(".", "<TEMP>"); var temp2 = temp.Replace(",", "."); var replaced = temp2.Replace("<TEMP>", ","); 
+4
source share

Not sure what 100.00.56 means, did you mean 10.000.56?

To answer your question:

For such a simple task, why use RegEx? You can make it a lot easier:

 string oldValue = "100,00.56"; char dummyChar = '&'; //here put a char that you know won't appear in the strings var newValue = oldValue.Replace('.', dummyChar) .Replace(',', '.') .Replace(dummyChar, ','); 

Edit I agree with @Oded, for formatting numbers use the CultureInfo class.

+4
source share

Not a RegEx solution, but from my experience - more correct:

 public static string CheckDecimalDigitsDelimiter(this string instance) { var sv = new CultureInfo("sv-SE"); var en = new CultureInfo("en-US"); decimal d; return (!Decimal.TryParse(instance, NumberStyles.Currency, sv, out d) && Decimal.TryParse(instance, NumberStyles.Currency, en, out d)) ? d.ToString(sv) : // didn't passed by SV but did by EN instance; } 

What does this method do? This ensures that if the given string is incorrect in the string Sweden, but the correct English version - convert it to Sweden, for example. 100,00 -> 100,00 , but 100.00 -> 100,00 .

+4
source share

Don't rely on RegExp for this kind of thing :) Use assembly in fx cultures:

 decimal s = decimal.Parse("10,000.56", NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US")); string output = s.ToString("N",CultureInfo.GetCultureInfo("da-DK")); 

ru-US will parse it correctly, and da-DK uses a different view. I live in DK and therefore use it, but you must use a culture that is suitable for your products.

+3
source share

All Articles