This is consistent with the above example, but NOT MORE. (I THINK)
myDecimal.ToString("#.######")
What other requirements exist? Are you going to manipulate values ββand display managed values ββby that number of decimal places?
An alternative answer includes recursion, for example:
//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 need 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( "." ) && for a comment from Jon Skeet, but keep in mind that this will make it incredibly slow. If you know that you will always have a decimal code and there is no such case as myDecimal = 6000; , you can refuse this test, or you can do it in a class and have several private methods based on whether the input contains a decimal number, etc. I was the simplest and "it works" instead of Enterprise FizzBuzz
jcolebrand Nov 28 '10 at 20:09 2010-11-28 20:09
source share