Question

I am working on a C# application. I want to change number decimal figure with comma(,) where i have dot(.) using regular expression.

For example:

Price= 100,00.56

As this international rule of representing numeric values but I Sweden they have different ways for numbers Like

Price= 100.00,56

So i want to change dot(.) into comma(,) and comma(,) into dot(.) using RegEx. Could guide me about this.

Was it helpful?

Solution

When formatting numbers, you should use the string format overload that takes a CultureInfo object. The culture name for swedish 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 out numbers should also be done with CultureInfo.

OTHER TIPS

Also have a look at

System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator

Not sure what 100,00.56 represents, did you mean 10.000,56?
To answer your question:

For such a simple task, why use RegEx? You can do it much 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.

You can do this even without regex. For example

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

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? It ensures that if given string is incorrect Sweden string but is correct English - convert it to Sweden, e.g. 100,00 -> 100,00 but 100.00 -> 100,00.

Do not rely on RegExp for this kind of thing :) Use the build in cultures fx:

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

en-US will parse it correctly and da-DK uses the other kind of representation. I live in DK and therefore use that but you should use the culture which fits your output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top