-2

Are there any options for setting the default format when writing a double value to the console?

I have many double values to output to the console, and I need set the format to two decimal places on all of them, like Math.Round(number, 2).

Can I set this for all of them?

Right now I'm using:

Console.WriteLine("{0} x {1} x {2}",
                  Math.Round(a, 2), Math.Round(b, 2), Math.Round(c, 2));
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Peter
  • 11
  • 1

2 Answers2

3

Console.Writeline is just a function that outputs a string to the console. You can't change the "default" format for strings, so the basic answer to your question is NO.

However, your code can be simplified. By specifying a format string, you can avoid the use of Math.Round:

Console.WriteLine("{0:D2} x {1:D2} x {2:D2}", a, b, c);

"D2" is a decimal number out to 2 decimal places. See MSDN for other common formatting strings. Note that this works because Console.Writeline invokes String.Format under the hood.

As to why you can't do this; String.Format takes each argument and calls ToString on it. It then applies the formatting string (if any). You can't override ToString for a double so there is no way to change the "default".

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • I know that, but it not clean code. When I find that I need at all to show 3 decimal numbers so I have a problem, so I have at least constat and the use of Math.Round – Peter Oct 28 '14 at 00:02
  • @Peter How is that not clean? You can't force `double.ToString` to behave differently. I don't know what you expect here. I did add an explanation of this to my answer; hopefully its useful for you. – BradleyDotNET Oct 28 '14 at 00:06
1

Another possibility, if you find that you do have to use Math.Round (or perform some other operation on the numbers) is to write your own method for rounding the numbers.

This will round each number you pass in, then create a single string out of the numbers (placing an "x" between each one, similar to your output):

private static void WriteNumbers(IEnumerable<double> numbers)
{
    Console.WriteLine(string.Join(" x ", numbers.Select(n => Math.Round(n, 2))));
}

And then just pass it an array of doubles to operate on:

WriteNumbers(new[] {2.2344, 3.323, 5.23432});

Output:

2.23 x 3.32 x 5.23

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Thats possible, but it not be used if I have Console.WWriteLine("{0} {1} {2}", doubleVariable, stringVarible, doubleVariable2) – Peter Oct 28 '14 at 00:16