-6

I want to print a double as string, in a way that it allways shows 2 fractional digits, even if they are "00".

The expected output is 30.00 but the actual result is 30.

class Program
{
    static void Main(string[] args)
    {            
        short a = 10;
        int b = 20;
        double d = (double)(a + b);
        Console.WriteLine(d);
        Console.ReadKey();
    }
}
Tobias Theel
  • 3,088
  • 2
  • 25
  • 45
Niru
  • 17

2 Answers2

2

Update

As the problem was not the "converting" from int/short to double, but the formatting of the resulting string, when printing i updated the Answer.


There is no need to explicitly Cast/Convert an Int/Short into Double. That is implicitly done.

Implicit Cast works like shown below:

  int i = 3;
  double d = i;

Working example of your code: There is no need for an explicit cast.

class Program
{
    static void Main(string[] args)
    {            
        short a = 10;
        int b = 20;
        double d = a + b;
        Console.WriteLine( d.ToString("0.00"));
        Console.ReadKey();
    }
}

Result:

Result of the code above

Or you could use Convert.ToDouble() Example usage:

  int i = 3;
  double x = Convert.ToDouble(i);

Have a look at this and this for further explanation.

Update 2

Thanks to Rand Random for the following hint.

You can also use d.ToString("N2"), that way you get thousand separators.

For further Information about the difference of "0.00" and "N2" have a look at this post.

Tobias Theel
  • 3,088
  • 2
  • 25
  • 45
0

Just Change this line

Console.WriteLine(d);

To this

Console.WriteLine( d.ToString("0.00"));

This should work and will get output as 30.00. It makes use of formatting the string by the given format provider.

Tobias Theel
  • 3,088
  • 2
  • 25
  • 45
AJRakesh
  • 71
  • 3
  • 15