Monday, 19 August 2013

How could I convert a value that looks like a double into an unsigned long, but properly?

How could I convert a value that looks like a double into an unsigned
long, but properly?

I am programming in C# and what I am trying to do is convert this string
containing a value that seems to be a double, so what I did first was
convert the string into a double, then I typecast the double into an
unsigned long. Only problem is that the unsigned long is always either a
few digits greater or a few digits lower that the value I am suppose to be
receiving. But after I typecast the double into an unsigned long, I
convert it into a hexadecimal string and pad it.
Here is an example of what I am doing:
string ValueToParse = "2.53327490880368E+15";
double nValue1 = double.Parse(ValueToParse);
ulong nValue2 = (ulong)nValue1;
string str = nValue2.ToString("X16");
Here are the results of this:
string str = "00090000070EC260";
This is the problem:
Right now this seems as if nothing is wrong to the average programmer.
But what I'm trying to do is get it so that the value being returned is
the real result that I am looking for which is 00090000070EC258 - NOT -
00090000070EC260 and I have no clue to what may be causing this difference
in values.
The only assumption I can think of that may be causing this value
difference is something to do with typecasting the double to an unsigned
long and within the process of the value being converted, something with
the precision of the double is messing things up.
So please if anybody may know what's going wrong or has any ideas about
what may be going wrong, please do respond. I appreciate any help that can
be provided. Thanks. :)

No comments:

Post a Comment