c# - string.format() 不显示值

标签 c# .net

谁能告诉我为什么这个 string.Format() 不显示第一个值?

long countLoop = 0;
long countTotal = 3721;

string.Format("Processed {0:#,###,###} lines of {1:#,###,###} ({2:P0})", countLoop, countTotal, ((double)countLoop / countTotal));

我得到的结果是

Processed  lines of 3,721 (0 %) 

但是如果我用数字 1 替换 countTotal

string.Format("Processed {0:#,###,###} lines of {1:#,###,###} ({2:P0})", 1, countTotal, ((double)countLoop / countTotal));

我明白了

处理了 1 行 3,721 (0 %)。

关于 string.Format 有什么我不知道的吗?

最佳答案

请参阅 the "#" custom format specifier 上的文档:

Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string.

如果您想在这种情况下显示“0”,请查看 the "0" custom format specifier :

If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string.

这应该适合你:

string.Format(
    "Processed {0:#,###,##0} lines of {1:#,###,###} ({2:P0})", 
    countLoop, countTotal, ((double)countLoop / countTotal));

关于c# - string.format() 不显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18262506/

相关文章:

c# - C#线程和类问题

c# - 转换为通用基类失败

.net - 如何让 SignalR 订阅 Redis channel ?

.net - WPF XAML 字符串格式。逃脱 %

c# - ASP.net 中的转发器

C# 值不在预期范围内

c# - ASMX Web 服务的自定义 WSDL

c# - 我在 C# OpenAI 库中收到 HttpClient.Timeout 错误

c# - 使用 JSON 反序列化方法时 VS 2013 崩溃

c# - Csharp - 将单数转换为十进制而不转换为字符串