caras caras - 2 months ago 23
C# Question

string to decimal using extension methods

My string is

1799.00


I want to like this:
1.799,00


But i cannot convert this method.

I'm using this function.

public static decimal ToDecimal(this object str)
{
if (str != null)
{
try
{
return Convert.ToDecimal(str, new CultureInfo("tr-TR"));
}
catch (Exception)
{
return 0;
}
}
else
{
return 0;
}
}

Answer

You are, probably, looking for changing formats. Given a decimal as a string in invariant culture representation ("1799.00") you want a string, but in Turkish cutrure representation: ("1.799,00")

  // you want to return string in Turkish culture, right?
  public static string ToTuskishDecimal(this object value) {
    if (null == value)
      return null; // or throw exception, or return "0,00" or return "?"

    try {
      return Convert
       .ToDecimal(value, CultureInfo.InvariantCulture)
       .ToString("N", CultureInfo.GetCultureInfo("tr-TR")); 
    }
    catch (FormatException) {
      return "0,00"; // or "?"
    } 
  }

Test:

 decimal d = 1799.00m;
 string s = d.ToString(CultureInfo.InvariantCulture);

 // 1.799,00
 Console.Write(d.ToTuskishDecimal());
 // 1.799,00
 Console.Write(s.ToTuskishDecimal());

In case you want to return decimal you have to format it manually when printing out:

 public static decimal ToDecimal(this object value) {
   if (null == value)
     return 0.00m;

   try {
     return Convert.ToDecimal(value, CultureInfo.InvariantCulture);
   }
   catch (FormatException) {
     return 0.00m; 
   } 
 }

...

 // return me a decimal, please
 decimal d = "1799.00".ToDecimal();
 // when printing decimal, use Turkish culture
 Console.Write(d.ToString("N", CultureInfo.GetCultureInfo("tr-TR")));

you can specify Turkish culture as a default one for the entire thread:

 Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR");
 ...
 // now you don't have to mention Turkish culture
 // ...but still have to specify the format
 Console.Write(d.ToString("N"));
Comments