[ACCEPTED]-Simple way to trim Dollar Sign if present in C#-c#
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.
You could also use
string trimmed = (dr as string).Trim('$');
or
string trimmed = (dr as string).TrimStart('$');
0
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:
((String)dr[columnName]).RemoveNonNumeric();
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.
Regex would work.
Regex.Replace(theString, "$", "");
But 1 there are multiple ways to solve this problem.
dr[columeName].ToString().Replace("$", String.Empty)
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.