Pinchy
Pinchy

Reputation: 1536

Remove dot character from a String C#

Assume I have a string "2.36" and I want it trimmed to "236"

I used Trim function in example

String amount = "2.36";
String trimmedAmount = amount.Trim('.'); 

The value of trimmedAmount is still 2.36

When amount.Trim('6'); it works perfectly but with '.'

What I am doing wrong?

Thanks a lot Cheers

Upvotes: 18

Views: 56415

Answers (4)

Ste
Ste

Reputation: 1136

String.Trim removes leading and trailing whitespace. You need to use String.Replace()

Like:

string amount = "2.36"; 
string newAmount = amount.Replace(".", ""); 

Upvotes: 5

Guffa
Guffa

Reputation: 700680

If you want to remove everything but the digits:

String trimmedAmount = new String(amount.Where(Char.IsDigit).ToArray());

or:

String trimmedAmount = Regex.Replace(amount, @"\D+", String.Empty);

Upvotes: 7

ykatchou
ykatchou

Reputation: 3727

Two ways :

string sRaw = "5.32";
string sClean = sRaw.Replace(".", "");

Trim is make for removing leading and trailings characters (such as space by default).

Upvotes: 4

Oded
Oded

Reputation: 499242

Trimming is removing characters from the start or end of a string.

You are simply trying to remove the ., which can be done by replacing that character with nothing:

string cleanAmount = amount.Replace(".", string.Empty);

Upvotes: 60

Related Questions