C# 字符串格式化和填充

发布于 2024-08-17 05:40:01 字数 508 浏览 3 评论 0原文

看起来这应该是一件简单的事情,但我一直没能做到正确。我看过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 技术交流群。

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

发布评论

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

评论(2

笑,眼淚并存 2024-08-24 05:40:01

尝试

double d = 3.14;
Console.WriteLine("{0,10:0.000}", d);

P.S:看看这篇文章作为字符串格式化入门。另外, string.Format 应该允许您执行 sprintf 所做的一切 - 实际上更多......您还想做什么?

Try

double d = 3.14;
Console.WriteLine("{0,10:0.000}", d);

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?

谁的年少不轻狂 2024-08-24 05:40:01

有用的

|{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

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