user3020047
user3020047

Reputation: 888

C# datatype double not printing what I would expect

C# datatype double not printing what I would expect

 namespace test
 {
     class SampleProgram
     {
         static void Main(string[ ] args)
         {
            int i = 10;
            double d = 34.340;
            fun(i);
            fun(d);
         }

         static void fun(double d)
         {
            Console.WriteLine(d + " ");
         }
    }
}

Why doe this produce 10 34.34 instead of 10 34.340 ?

Upvotes: 0

Views: 94

Answers (2)

John Koerner
John Koerner

Reputation: 38077

To the computer a double with a value of 34.34, 34.340, 34.3400 are all equivalent and represented the same in memory.

What you are running into is the standard problem of the way the runtime gives data back is different than what to display to the user. The way to handle this is to leverage one of the many formatting tools provided by .Net.

You could use the ToString method on the double data type with a custom format string:

double value = 34.34;
Console.WriteLine(value.ToString("0.000"));   // 34.340

You could also use custom format string in String.Format:

double value = 34.34;
Console.WriteLine(String.Format("The value is {0:0.000}", value));

Upvotes: 1

Xilmiki
Xilmiki

Reputation: 1502

you have to apply a custom format to your double value, see string format options and example here http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

e.g. number.ToString("G", CultureInfo.InvariantCulture)

Upvotes: 0

Related Questions