【问题标题】:string.format() not showing valuesstring.format() 不显示值
【发布时间】:2013-08-15 21:51:57
【问题描述】:

谁能告诉我为什么这个 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 %) 

但如果我将 countTotal 替换为数字 1

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

我明白了

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

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

【问题讨论】:

  • 我在想 {0:#,##,###},当传递 0 作为值时,什么都没有......顺便说一句,不应该是第三个替换是数字 2?即,{3:P0} 应该是 {2:P0}?

标签: c# .net


【解决方案1】:

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

请注意,此说明符从不显示不是有效数字的零,即使零是字符串中唯一的数字。

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

如果正在格式化的值在格式字符串中出现零的位置有一个数字,则将该数字复制到结果字符串中;否则,结果字符串中将出现零。

这应该适合你:

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

【讨论】:

    【解决方案2】:

    将字符串格式更改为

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

    这将在 countLoop 为零时打印 0。

    正如其他人在我之前所说的那样,当 # 占位符不是有效数字时,它不会打印零。

    注意我已在格式字符串中修复了您的索引。 你只有三个参数,所以索引从 0 到 2 (而不是你最后的 3 ({3:P0})

    【讨论】:

    • 关注2:P0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2021-08-08
    相关资源
    最近更新 更多