Girish Girish - 19 days ago 5
C# Question

How to get decimal values with zero on adiition of double type in c#

Here below is the operations..

double d=4.0;
double dd=4.0;
double results=d+dd;


it gives at the time of execution

results => 8


Instead of

results => 8.0


I would like to get output like below

results => 8.0


Will anybody tell me how to get decimal value with zero's also

Answer

You should use decimal, not double for your requirement.

decimal d= 4.0M;
decimal dd=4.0M;
decimal results=(d+dd); //8.0

double is not completely accurate, use decimal instead

For money, always decimal. It's why it was created.

You hsould use decimal if you want more accurate results. If the exact value of numbers is not important, use double.double has better performance than decimal.

double, is implemented as binary fraction, cannot accurately denotes many decimal fractions.

You can refer this answer for better understanding.

Note: decimal has exponent base 10 and double has 2.

Although you can use ToString() as a heck.

double d= 4.0;
double dd=4.0;
double results=(d+dd);

string str = results.ToString("0.0"); //8.0

You can also use String.Format