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);
必要时仅包含数字.
如果您想要其他格式化双精度字符串的示例,请查看此 链接.
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 :)
这篇关于如何将双精度格式化为字符串并仅在必要时显示十进制数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将双精度格式化为字符串并仅在必要时显示十进制数字?


基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01