Convert.ToDouble in c# not giving right answer when accessing redis database

Im trying to convert a long string of numbers into a double in order to use that as an index to a redis database (redis requires a double) but the conversion isnt correct so the database fetch gets messed up.

Here is the code to convert the string into a double

string start="636375529204974172";
ulong istart = Convert.ToUInt64(start);   // result 636375529204974172
double dstart = Convert.ToDouble(istart); // result 6.3637552920497421E+17

as you can see the problem starts when i convert istart to a double as dstart, some of the least significant digits gets messed up, seems by the conversion introducing the E+17 in there.

I cant understand why, its a WHOLE NUMBER, no fractional part to create error so why it cant do it?

Does anybody knows how to fix the conversion from a string to double?

Jon Skeet
people
quotationmark

I cant understand why, its a WHOLE NUMBER, no fractional part to create error so why it cant do it?

Because it still only has 64 bits of information to play with, 52 of which are used for the mantissa, 11 of which are used for the exponent, and 1 of which is used for the sign.

Basically you shouldn't rely on more than 15 decimal digits of precision in a double. From the docs for System.Double:

All floating-point numbers also have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A Double value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

The first 15 significant digits of your value are correct - nothing is going wrong here. The nearest double value to your original value is exactly 636375529204974208. There is no double that precisely represents 636375529204974172.

people

See more on this question at Stackoverflow