Remove last characters from a string in C#. An elegant way?

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".

I did:

str = str.Remove(str.Length - 3, 3);

Is there a more elegant solution? Maybe using another function? -I don´t like putting explicit numbers-


Solution 1:

You can actually just use the Remove overload that takes one parameter:

str = str.Remove(str.Length - 3);

However, if you're trying to avoid hard coding the length, you can use:

str = str.Remove(str.IndexOf(','));

Solution 2:

Perhaps this:

str = str.Split(",").First();

Solution 3:

This will return to you a string excluding everything after the comma

str = str.Substring(0, str.IndexOf(','));

Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:

commaPos = str.IndexOf(',');
if(commaPos != -1)
    str = str.Substring(0, commaPos)

I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:

myInt = (int)double.Parse(myString)

This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.