Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 785
Mohsin JK Avatar asked Aug 04 '10 09:08

Mohsin JK


2 Answers

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.

like image 51
Oded Avatar answered Oct 11 '22 05:10

Oded


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.

like image 45
abatishchev Avatar answered Oct 11 '22 03:10

abatishchev