C# 字符串格式化和填充
看起来这应该是一件简单的事情,但我一直没能做到正确。我看过http://idunno.org/archive/2004/14/ 01/122.aspx供参考。
例子: 我想打印一个双精度值表,每个双精度输出具有 3 位小数精度,并占用 10 个空格(左对齐)。从概念上讲,我尝试了类似的方法,但它仅适用于精度或填充,而不适用于两者:
foreach(line in lines)
{
foreach (double val in line)
{
Console.Write("{0:0.000,-10}", val);
}
Console.WriteLine()
}
更新:我可以在非常简单的场景中使用 padleft/padright,如果我有更复杂的输出,它会变得不是很简洁。有没有类似sprintf的东西?
Seems like this should be something straightforward, but I haven't been able to get it right. I've looked at http://idunno.org/archive/2004/14/01/122.aspx for reference.
Example:
I would like to print a table of double values, with each double output having 3 decimal precision, and take up 10 spaces (left aligned). Conceptually, I tried something like this, but it only works with precision OR padding, not both:
foreach(line in lines)
{
foreach (double val in line)
{
Console.Write("{0:0.000,-10}", val);
}
Console.WriteLine()
}
Update: I can use padleft/padright in very simple scenarios, if i have more complicated output it becomes not very concise. Is there something similar to sprintf?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
P.S:看看这篇文章作为字符串格式化入门。另外, string.Format 应该允许您执行 sprintf 所做的一切 - 实际上更多......您还想做什么?
Try
P.S: have a look at this article as a primer on string formatting. Also,
string.Format
should allow you doing everything sprintf does - and actually more... what else are you trying to do?有用的
|{0,-10:0.00}| => |87,87 | - 带“-”
=> padRight<代码>|{0,10:0.000}| => | 87,878| - 没有“-” => padLeft
<代码>|{3,-10:0.###}| - ### - 仅在有意义的情况下才打印小数点“,”后的数字(非 0):87,8000 =>87,8
useful
|{0,-10:0.00}| => |87,87 | - With "-"
=> padRight|{0,10:0.000}| => | 87,878| - Without "-"
=> padLeft|{3,-10:0.###}| - ###
- prints numbers after decimal "," only if it is meaningful (not 0): 87,8000 =>87,8