格式 IEnumerable在控制台中显示时

发布于 2025-01-08 01:29:15 字数 348 浏览 2 评论 0原文

我必须将双精度数集合格式化为小数点后两位,并通过用逗号 (,) 分隔来将其显示在控制台应用程序中。

我使用了以下内容:

var result = GetResults() //returns 1.234125, 3.56345, 6.43254

Console.WriteLine(string.Join(",",result)

但是,这不会将值格式化为小数点后两位。我希望在控制台上显示 1.23,3.56,6.43。此外,“结果”集合中的元素范围可能为几千个双精度数。因此,我正在寻找一段优化的代码,它不涉及任何装箱,并且需要最短的时间将其自身显示到控制台。

谢谢, -麦克风

I have to format a collection of doubles to 2 decimal places and display it in a console app by seperating it with a comma (,).

I have used the following:

var result = GetResults() //returns 1.234125, 3.56345, 6.43254

Console.WriteLine(string.Join(",",result)

However this does not format the values to 2 decimal places. I'm looking to display 1.23,3.56,6.43 to the console. Also the elements in "result" collection could range for a few 1000 doubles.So I'm looking for an optimized piece of code which will not involve any boxing and will take the least time to display itself to the console.

Thanks,
-Mike

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

软甜啾 2025-01-15 01:29:15
String.Join(result.Select(d => d.ToString("0.00"))

自定义数字格式字符串

String.Join(result.Select(d => d.ToString("0.00"))

Custom Numeric Format Strings

睫毛溺水了 2025-01-15 01:29:15

Console 类有效地缓冲所有接收到的数据,因此多个 Console.Write 调用实际上不会降低性能。此外,您不必将所有文本都放在一大块中。所以我的答案是:

IEnumerable<double> result = new double[] { 1.1234, 2.2345, 3.3456 };
foreach (double item in result)
    Console.Write ("{0},", item.ToString("0.00"));
Console.WriteLine ();

显式的 double.ToString 调用可以避免不必要的装箱。但我建议您在使用更复杂的方法之前比较这两种方法的性能。

另请注意,在某些文化中,逗号已用作小数分隔符。

Console class effectively buffers all received data, so multiple Console.Write calls actually don't reduce permormance. Also you don't have to get all the text in one huge piece. So my answer is:

IEnumerable<double> result = new double[] { 1.1234, 2.2345, 3.3456 };
foreach (double item in result)
    Console.Write ("{0},", item.ToString("0.00"));
Console.WriteLine ();

Explicit double.ToString call allows to avoid unnecessary boxing. But I suggest you to compare performance in both ways before using more complicated one.

Also note that in some cultures a comma is already used as fractional separator.

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