[c#] 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-

This question is related to c# .net string

The answer is


You can use TrimEnd. It's efficient as well and looks clean.

"Name,".TrimEnd(',');

You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.

string var = var.Substring(0, var.LastIndexOf(','));


Perhaps this:

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

Try the following. It worked for me:

str = str.Split(',').Last();

String.Format("{0:0}", 123.4567);      // "123"

If your initial value is a decimal into a string, you will need to convert

String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture))  //3.5

In this example, I choose Invariant culture but you could use the one you want.

I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.

Edit: You can also use Truncate to remove all after the , or .

Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));

Use:

public static class StringExtensions
{
    /// <summary>
    /// Cut End. "12".SubstringFromEnd(1) -> "1"
    /// </summary>
    public static string SubstringFromEnd(this string value, int startindex)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Substring(0, value.Length - startindex);
    }
}

I prefer an extension method here for two reasons:

  1. I can chain it with Substring. Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
  2. Speed.

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.


Use lastIndexOf. Like:

string var = var.lastIndexOf(',');

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript