1

having a string that's looking like "1.900,00". How could I format this string to a decimal of 1900?

Using:

decimal.TryParse("1.900,00", out var vkp)

Will give me a false result. How can I handle this?

Here's a URL to the online C# compiler: https://dotnetfiddle.net/B5EyyC

MrSilent
  • 564
  • 10
  • 28

4 Answers4

4

You could try using a CultureInfo that uses '.' as thousands separator and ',' as decimal separator (for example "de-DE"). And also the appropriate NumberStyles.

string input = "1.900,00";
decimal.TryParse(input, 
    NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint, 
    CultureInfo.GetCultureInfo("de-DE"), out var output);

You can even create your very own instance of NumberFormatInfo where you can specify the NumberDecimalSeparator and NumberGroupSeparator any way you like.

Corak
  • 2,688
  • 2
  • 21
  • 26
0

try this:

        string s = "1.900,00";
        s = s.Substring(0, s.LastIndexOf(",")).Replace(".", "") + "." + s.Substring(s.LastIndexOf(",") + 1);
        decimal vkp = 0;
        decimal.TryParse(s, out vkp);
Hasan Mahmood
  • 978
  • 7
  • 10
0

I guess you could try the following:

string number = "1.900,00";
decimal.TryParse(number.Split(",")[0].Replace(".",""), out var vkp);

In case you need a more foolproof checking you could try making a function that checks whether or not the string contains a ',' character.

public static bool ToDouble(string s, out double d)
{
   if (s.Contains(","))
      return double.TryParse(s.Split(",")[0].Replace(".", ""), out d);

   return double.TryParse(s, out d);
}

Also you can get the decimal separator of you localization settings via:

string dsep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
0

Decimal.TryParse doc

//using System.Globalization;   
NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
CultureInfo culture = CultureInfo.CreateSpecificCulture("es-ES");               
Decimal vkp;        
Decimal.TryParse("1.900,00", style, culture, out vkp);
B. Lec
  • 312
  • 2
  • 13