2

I'm trying to add two double numbers say, 1234567890123456.00 and 1.00 and the summation will be stored into a string.

Results are as follows:

1234567890123456.00 + 1.00 = 1234567890123457.00

Obvious that it will print as 1.23456789012346E+15 in double form.

But if I'm trying to convert it to string by using method ToString("F") or ToString("#") it results 1234567890123460.00. Where I'm losing 7(the last digit)?

static void Main(string[] args)
{
     double d = 1234567890123456;
     double d2 = 1;
     double d3 = d + d2;

     Console.WriteLine(d3);
     Console.WriteLine(d3.ToString("F"));
}

Please help me to correct the code or to find an alternative.

Micha
  • 5,117
  • 8
  • 34
  • 47
Rahul Chakrabarty
  • 2,149
  • 7
  • 39
  • 70

2 Answers2

1

Double type has 15-16 decimal precision digits and your d value has 16 significant decimal digits, so you are stressing that limit:

double d = 1234567890123456;

That limit (of the significant digits) comes from the mantissa which in the IEEE 754 binary64 standard is actually 15.95 significant decimal digits.

Decimal could be a good alternative.

0
static void Main(string[] args)
{
     double d = 1234567890123456;
     double d2 = 1;
     double d3 = d + d2;

     Console.WriteLine(d3);
     Console.WriteLine(d3.ToString("R"));
}

R - round-trip solved my problem and I'm getting expected result as 1234567890123457

Binary floating point and .NET

Rahul Chakrabarty
  • 2,149
  • 7
  • 39
  • 70