How do I format a C# decimal to remove extra following 0's?

Scott Stafford picture Scott Stafford · Jan 24, 2011 · Viewed 82.9k times · Source

I want to format a string as a decimal, but the decimal contains some following zeros after the decimal. How do I format it such that those meaningless 0's disappear?

string.Format("{0}", 1100M);
string.Format("{0}", 1100.1M);
string.Format("{0}", 1100.100M);
string.Format("{0}", 1100.1000M);

displays:

1100
1100.1
1100.100
1100.1000

but I want it to be:

1100
1100.1
1100.1
1100.1

For reference, here are other questions that are essentially duplicates of this, that I've found thanks to answers given here:

Answer

Herohtar picture Herohtar · Jan 24, 2011

You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).

The line of code to produce what you want is number.ToString("G29"), where number is your original decimal.

Be aware that any numbers smaller than 0.0001 will be converted to scientific notation. More details on how this formatter works can be found at the reference link above.