Wednesday, February 9, 2011

Simple way to trim Dollar Sign if present in C#

I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.

So something like:

dr.ToString.Substring(1, dr.ToString.Length);

But more conditionally in case the dollar sign ever made an appearance again.

I am trying to do this with explicitly defining another string.

  • Convert.ToString(dr(columnName)).Replace("$", String.Empty)

    -- If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.

    From StingyJack
  • Regex would work.

    Regex.Replace(theString, "$", "");

    But there are multiple ways to solve this problem.

    From itsmatt
  • dr[columeName].ToString().Replace("$", String.Empty)

    From devmode
  • Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.

    Brian G : The DB query is a API controlled by a third party that has thousands of customers. I guess i should have noted that though.
    Abyss Knight : Because storing invalid data is, well, wrong.
    From Kwirk
  • If you are using C# 3.0 or greater you could use extension methods.

    public static string RemoveNonNumeric(this string s)
    {
       return s.Replace("$", "");
    }
    

    Then your code could be changed to:

    ((String)dr[columnName]).RemoveNonNumeric();
    

    This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.

    Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.

    Brian G : Thats cool! Thanks
    From Shaun Bowe
  • You could also use

    string trimmed = (dr as string).Trim('$');
    

    or

    string trimmed = (dr as string).TrimStart('$');
    
    From hangy

0 comments:

Post a Comment