我如何格式化双为字符串,并只显示必要时小数位数? [英] How do I format a double to a string and only show decimal digits when necessary?
问题描述
我有这样的代码:
lblFranshizShowInvwNoskhehEdit.Text = string.Format("{0:n}",
(double)(int.Parse(drDarman["FranshizDarsad"].ToString()) *
Convert.ToInt64(RadNumerictxtPayInvwNoskhehEdit.Text)) / 100);
但 {0:N0}
字符串格式强制标签的文本不具有小数位数和 {0:N}
字符串格式强制标签的文本有2个十进制数字(默认)
But {0:n0}
string format forces the label's text to not have decimal digits and {0:n}
string format forces the label's text to have 2 decimal digits (default).
在我的情况我只想小数位数,必要时/没有四舍五入他们/我该怎么办呢?
In my scenario I just want decimal digits when necessary / without rounding them / how can I do that?
推荐答案
您可以这样做:
string.Format("{0}", yourDouble);
这将只包括数字在必要时。
It will include only digits when necessary.
如果您想格式化双打串看看这个链接的其他例子。
If you want other examples of formatting doubles to string check out this link.
编辑:基于您的评论你想要的,
分隔符,所以你可以这样做:
Based on your comment you want the ,
seperator so you could do:
string.Format("{0:0,0.########}", yourDouble);
只要把尽可能多的#
的最大值小数点后的位数要显示。它只会在必要的时候显示的数字,但到最大的数字依据是有多少#
用户在使用的格式。在#
表示只显示一个数字,如果必要的,这样,如果你给一个数字,如 123
不带小数,它会显示为 1,234
,但如果你给它 1234.456
,它将会显示为 1,234.456
。如果你超越了最大的数字指定,他们将四舍五入
Just put as many #
for the max number of decimal places you want to show. It will only show the digits when necessary but up to the maximum digits based on how many #
you include in the format. The #
means only show a digit if necessary so if you give a number like 123
with no decimal, it will display as 1,234
but if you give it 1234.456
, it will display as 1,234.456
. If you go beyond the max digits you specified they will be rounded.
编辑::要解决您的双零方案只是将其更改为:
To fix your double zero scenario just change it to:
string.Format("{0:#,0.########}", yourDouble);
这应该很好地工作现在:)
That should work perfectly now :)
这篇关于我如何格式化双为字符串,并只显示必要时小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!