Remove Trailing Zeroes From a String in C# using Regular Expressions

The code sample is that of a function RemoveTrailingZeros in C#, that takes a string input and removes all trailing zeros in it.

The code uses the Regex object provided by the .Net class library. Regular Expressions optimize the operation of "searching patterns" in a string. The following code can also be taken as an example to remove any character (trailing) from a string. The only change require will be that we need to change the Regular Expression.


//Regex is in System.Text.RegularExpressions namespace
public string RemoveTrailingZeroes(string input)
{
Regex reg1 = new Regex("\\.\\d*(?<1>0+)[^\\d]*$", RegexOptions.IgnoreCase);

Match m = reg1.Match(input);
if( m.Success )
{
input = input.Replace(m.Groups["1"].Value, "");
Regex reg2 = new Regex("(?<1>\\.)[^\\d]*$", RegexOptions.IgnoreCase);
m = reg2.Match(input);

if( m.Success )
{
input = input.Replace(".", "" );
}
Regex reg3 = new Regex("\\d", RegexOptions.IgnoreCase );
m = reg3.Match(input);
if( !m.Success )
{
input = "0" + input;

}

}
if(input.StartsWith("."))
input = "0" + input;

return input;
}


Comments

Author: Dan08 May 2009 Member Level: Bronze   Points : 1

This might be easier and faster:

public string RemoveTrailingZeroes(string s)
{
s = s.TrimStart('0').TrimEnd('0', '.');
if(s.StartsWith(".")) s = "0" + s;
return s;
}

Guest Author: Pitrs8103 Jan 2012

Not even one method works correctly.

First (using regex) doesn't work for numbers like 1.1010 (output is 1.11).
Second (using trim) doesn't work for numbers like 7000.00 (output is 7).



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: