如何将双精度型格式化为字符串并仅在必要时显示十进制数字?

发布于 2024-09-09 19:00:00 字数 383 浏览 2 评论 0原文

我有这样的代码:

lblFranshizShowInvwNoskhehEdit.Text = string.Format("{0:n}",
    (double)(int.Parse(drDarman["FranshizDarsad"].ToString()) * 
        Convert.ToInt64(RadNumerictxtPayInvwNoskhehEdit.Text)) / 100);

但是 {0:n0} 字符串格式强制标签的文本不包含十进制数字,而 {0:n} 字符串格式强制标签的文本包含十进制数字2 位小数(默认)。

在我的场景中,我只需要必要时的十进制数字/不四舍五入/我该怎么做?

I have code like:

lblFranshizShowInvwNoskhehEdit.Text = string.Format("{0:n}",
    (double)(int.Parse(drDarman["FranshizDarsad"].ToString()) * 
        Convert.ToInt64(RadNumerictxtPayInvwNoskhehEdit.Text)) / 100);

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏了南城 2024-09-16 19:00:00

您可以这样做:

string.Format("{0}", yourDouble);

必要时它将仅包含数字。

如果您想要其他将双精度数格式化为字符串的示例,请查看此链接

编辑:根据您的评论,您需要 , 分隔符,这样您就可以这样做:

string.Format("{0:0,0.########}", yourDouble);

只需输入尽可能多的 # 作为您的最大小数位数想要展示。它只会在必要时显示数字,但最多显示最大数字,具体取决于您在格式中包含的 # 数量。 # 表示仅在必要时显示一个数字,因此,如果您给出像 123 这样不带小数的数字,它将显示为 1,234 但如果您给它1234.456,它将显示为1,234.456。如果超出指定的最大位数,它们将被四舍五入。

编辑:要修复双零场景,只需将其更改为:

string.Format("{0:#,0.########}", yourDouble);

现在应该可以完美运行:)

You can just do:

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.

EDIT: Based on your comment you want the , seperator so you could do:

string.Format("{0:0,0.########}", yourDouble);

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.

EDIT: To fix your double zero scenario just change it to:

string.Format("{0:#,0.########}", yourDouble);

That should work perfectly now :)

荆棘i 2024-09-16 19:00:00

这是我的:

string.Format("{0:n2}", double);

this is mine :

string.Format("{0:n2}", double);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文