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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With