maxspan maxspan - 2 months ago 7
C# Question

showing decimal zero of a double variable in C#

I am trying to get decimal zero for a double variable. below is my code.

double d = 4.0;
double inputDouble = 4.0;
Console.WriteLine(d+ inputDouble);


I am getting 8 as output I want 8.0 as output. How I can achieve this.

Answer

Use the string.Format(string, object) method and set the string format to "{0:N1}" to have 1 decimal point.

    double d = 4.0;
    double inputDouble = 4.0;
    Console.WriteLine(string.Format("{0:N1}", d + inputDouble));