A simple way to crop a dollar sign if present in C #

I have a DataRow, and I get one of the elements, which is a dollar sign amount. I call toString. Is there any other method that I can call to remove the dollar sign, if any.

So something like:

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

But more conditionally, if the dollar sign reappears.

I am trying to do this with an explicit definition of another string.

+4
source share
6 answers
Convert.ToString(dr(columnName)).Replace("$", String.Empty) 

- If you are working with a data table, you need to delete the value (by default its Object) in the row, so that you are already creating a row, and then another with a replacement. There is no other way around this, but you will only see differences in performance when dealing with tens of thousands of operations.

+17
source

You can also use

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

or

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

If you are using C # 3.0 or higher, you can 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 will allow you to subsequently change the implementation of RemoveNonNumeric to remove things like commas or $ signs in foreign currency, etc.

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

+5
source

Regex will work.

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

But there are several ways to solve this problem.

+3
source

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

+2
source

Why don't you update the database query so that it does not return a dollar sign? This way you don't need futz with it in your C # code.

0
source

Source: https://habr.com/ru/post/1277336/


All Articles