This meets the example given but POORLY. (I THINK)
myDecimal.ToString("#.######")
What other requirements are there? Are you going to manipulate the values and show the manipulated values to this number of decimals?
Alternate answer involves recursiveness, like so:
//use like so:
myTextbox.Text = RemoveTrailingZeroes( myDecimal.ToString() );
private string RemoveTrailingZeroes(string input) {
if ( input.Contains( "." ) && input.Substring( input.Length - 1 ) == "0" ) { //test the last character == "0"
return RemoveTrailingZeroes( input.Substring( 0, input.Length - 2 ) )
//drop the last character and recurse again
}
return input; //else return the original string
}
And if you wanted an extension method, then this is an option
//use like so:
myTextbox.Text = myDecimal.ToString().RemoveTrailingZeroes();
private string RemoveTrailingZeroes(this string input) {
if ( input.Contains( "." ) && input.Substring( input.Length - 1 ) == "0" ) { //test the last character == "0"
return RemoveTrailingZeroes( input.Substring( 0, input.Length - 2 ) )
//drop the last character and recurse again
}
return input; //else return the original string
}
Added input.Contains( "." ) &&
per comment from Jon Skeet, but bear in mind this is going to make this incredibly slow. If you know that you'll always have a decimal and no case like myDecimal = 6000;
then you could drop that test, or you could make this into a class and have several private methods based on whether the input contained a decimal, etc. I was going for simplest and "it works" instead of Enterprise FizzBuzz