简体   繁体   中英

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.

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 .

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, ',');

I agree with @Oded, for formatting numbers use the CultureInfo class. 我同意@Oded,要格式化数字,请使用CultureInfo类。

也看看

System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator

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

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