Caner
Caner

Reputation: 873

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;
    }
}

Upvotes: 2

Views: 2740

Answers (3)

Greg Uretzky
Greg Uretzky

Reputation: 62

I wrote another simple example to obtain a decimal value in Turkish format:

decimal value = 1700.00m;
Console.WriteLine(value.ToString("N", CultureInfo.GetCultureInfo("tr-TR")));

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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"));

Upvotes: 3

lyrqs
lyrqs

Reputation: 78

I use this to obtain a decimal value:

public static decimal toDecimal( string s ) {
    decimal res = 0;
    decimal.TryParse(s.Replace('.', ','), out res);
    return res;
}

In case you want to show the decimal value on the format you ask, try this:

toDecimal("1700.99").ToString("N2") 

you will obtain the "1.700,99" string.

Upvotes: 1

Related Questions