格式 IEnumerable在控制台中显示时
我必须将双精度数集合格式化为小数点后两位,并通过用逗号 (,) 分隔来将其显示在控制台应用程序中。
我使用了以下内容:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
自定义数字格式字符串
Custom Numeric Format Strings
Console
类有效地缓冲所有接收到的数据,因此多个Console.Write
调用实际上不会降低性能。此外,您不必将所有文本都放在一大块中。所以我的答案是:显式的 double.ToString 调用可以避免不必要的装箱。但我建议您在使用更复杂的方法之前比较这两种方法的性能。
另请注意,在某些文化中,逗号已用作小数分隔符。
Console
class effectively buffers all received data, so multipleConsole.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: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.