如何格式化C#小数点以除去多余的下面的0? [英] How do I format a C# decimal to remove extra following 0's?

查看:1541
本文介绍了如何格式化C#小数点以除去多余的下面的0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串格式化为十进制,但小数点后面包含一些下面的零。如何格式化这些无意义的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

作为参考,这里还有其他一些本质上重复的问题,我发现这里给出了答案:




ToString()与 来实现所需的结果。以指定的精度使用此格式字符串时,尾随零将被截断。为了防止在任何情况下四舍五入,你将需要设置精度为允许的最大小数(29)。

产生你想要的代码行 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:

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆