[ACCEPTED]-Simple way to trim Dollar Sign if present in C#-c#

Accepted answer
Score: 18
Convert.ToString(dr(columnName)).Replace("$", String.Empty)

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

Score: 8

You could also use

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


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


Score: 7

If you are using C# 3.0 or greater you could 8 use extension methods.

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

Then your code could be changed to:


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

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

Score: 3

Regex would work.

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

But 1 there are multiple ways to solve this problem.

Score: 2

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


Score: 0

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

More Related questions