Search code examples
c#stringglobalization

Converting string to currency and globalization issue


I have this:

var pl = new CultureInfo("pl-PL");
decimal valsue = decimal.Parse("2,25 PLN", pl);

It works ok if i don't put "PLN" into my string. But PLN is currency in my country and i think that it should parse, so maybe i am doing something wrong? Is there any option to parse this into decimal with "PLN" attached to the string?


Solution

  • If you take a look at your CultureInfo's NumberFormat object, this will yield some clues about how it intends to parse values. In particular, NumberFormat.CurrencySymbol for the "pl-PL" culture is .

    In other words, this expression would parse successfully: decimal.Parse("2,25 zł", pl);

    If you prefer to use PLN as the currency symbol (technically, it's the currency code), it is possible to configure a custom NumberFormat, like so:

    var pln = (NumberFormatInfo) pl.NumberFormat.Clone(); // Clone is needed to create a copy whose properties can be set.
    pln.CurrencySymbol = "PLN";
    decimal valsue = decimal.Parse("2,25 PLN", NumberStyles.Currency, pln);
    

    But note the usage of NumberStyles.Currency in the Parse call: by default, decimal.Parse accepts only strings containing numeric values, without currency formatting.