471,603 Members | 1,463 Online

Outputting a double number with three decimal places

Hi

I'm really stuck outputting a double number to the console with three
decimal places if the furthest right value is a zero.

I can coutput the number 4.546 as 4.546 but then if I output 0.220 it comes
out as 0.22 and drops the zero. Also, outputting 1.000 outputs as 1.

How can I format it to include the zeros?

Thanks
Jan 5 '06 #1
2 2666
Andy <An**@discussions.microsoft.com> wrote:
I'm really stuck outputting a double number to the console with three
decimal places if the furthest right value is a zero.

I can coutput the number 4.546 as 4.546 but then if I output 0.220 it comes
out as 0.22 and drops the zero. Also, outputting 1.000 outputs as 1.

How can I format it to include the zeros?

Have you tried using "0.000" as a format specifier? For instance:

using System;

class Test
{
static void Main()
{
Display (0.22);
Display (4.546);
}

static void Display(double d)
{
Console.WriteLine ("{0:0.000}", d);
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Jan 5 '06 #2

"Jon Skeet [C# MVP]" wrote:
Andy <An**@discussions.microsoft.com> wrote:
I'm really stuck outputting a double number to the console with three
decimal places if the furthest right value is a zero.

I can coutput the number 4.546 as 4.546 but then if I output 0.220 it comes
out as 0.22 and drops the zero. Also, outputting 1.000 outputs as 1.

How can I format it to include the zeros?

Have you tried using "0.000" as a format specifier? For instance:

using System;

class Test
{
static void Main()
{
Display (0.22);
Display (4.546);
}

static void Display(double d)
{
Console.WriteLine ("{0:0.000}", d);
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet

That is brilliant. It worked a treat. Thank you very much.
Jan 6 '06 #3