如何格式化C#小数点以除去多余的下面的0? [英] How do I format a C# decimal to remove extra following 0's?
问题描述
我想将一个字符串格式化为十进制,但小数点后面包含一些下面的零。如何格式化这些无意义的0消失?
string.Format({0},1100.1M);
string.Format({0},1100.100M);
string.Format({0},1100.1000M);
显示:
1100
1100.1
1100.100
1100.1000
但我希望它是:
1100
1100.1
1100.1
1100.1
作为参考,这里还有其他一些本质上重复的问题,我发现这里给出了答案:
产生你想要的代码行 number.ToString(G29)
,其中 number
是您的原始小数。
请注意,小于0.0001的数字将转换为科学记数法。有关这个格式化程序如何工作的更多细节可以在上面的参考链接中找到。
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:
- Parse decimal and filter extra 0 on the right?
- Best way to display decimal without trailing zeroes
- How can I strip zeros and decimal points off of decimal strings?
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.
这篇关于如何格式化C#小数点以除去多余的下面的0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!