1

I used stackoverflow answers to figure out how to print my array to a single console line like this:

console.writeline(string.Join(",  ",myArray));

My array is decimal values (it is a double array) though and it prints very ugly.

Is there a way to round my array values inside this command?

Flux Capacitor
  • 1,215
  • 5
  • 24
  • 40

2 Answers2

3

Try to use

Console.WriteLine(string.Join(", ", myArray.Select(x => Math.Round(x, 2))));

It will round all values of myArray to two decimal places

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • Also, the [Math.Round Method (Decimal, Int32, MidpointRounding)](https://msdn.microsoft.com/en-us/library/ms131275(v=vs.110).aspx) is available for when "banker's rounding" is not the desired method. – Andrew Morton Jan 16 '17 at 22:06
1

A quickly way to do this is using linq or fluent syntax... The example above rounded by 2 decimal places...

console.writeline(string.Join(",  ",myArray.Select(q => Math.Round(q, 2)).ToList()));
  • I was going to recommend `"{0:N2}"` as the format. Here is a question on the difference: http://stackoverflow.com/questions/4506323/difference-between-tostringn2-and-tostring0-00 – Jared Stroebele Jan 16 '17 at 22:02
  • Does that *round* the numbers per se, or is it just printing the first two digits after the decimal point? That would usually be considered the "floor", which is perhaps one way of rounding numbers, but is probably not what people normally think of as rounding. – Eilon Jan 16 '17 at 22:03
  • @Eilon Tested it. `"{0:N2}"` and `"{0:0.00}"` both appear to round the decimal places. – Jared Stroebele Jan 16 '17 at 22:07
  • @JaredStroeb according to https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx it doesn't round, it just stops printing digits after some amount... – Eilon Jan 16 '17 at 23:05
  • @JaredStroeb oh actually I may have spoken too soon. The MSDN docs are rather confusing here. Some formats do round, some do not. So this might actually be correct, my apologies. – Eilon Jan 16 '17 at 23:08
  • Yes, you guys'r right. This way just format the value, for rounding the path for the success is Math.Round. Sorry for my misunderstood. :) – Rafael Ribeiro Jan 17 '17 at 00:08