I always convert bytes to double with System.BitConverter.ToDouble()
like this:
double value = BitConverter.ToDouble(flt, 0);//flt is an array of bytes.
But when I try to convert "8A 7F DA 0C 41 6D A6 40"(Little Endian),it become 2870.62705118949
.
Indeed, 2870.62705118949
is "8E 7F DA 0C 41 6D A6 40".
But what I want is 2870.6270511894881565
.How can I get the accurate value using C#?
When working with exact string representation, use "R" formatting:
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
"R" or "r" Round-trip Result: A string that can round-trip to an identical number.
In your case
Byte[] data = { 0x8A, 0x7F, 0xDA, 0x0C, 0x41, 0x6D, 0xA6, 0x40 };
Double value = BitConverter.ToDouble(data, 0);
Console.Write(value.ToString("R", CultureInfo.InvariantCulture)); // "R" formatting
And as you can see, the actual value is not 2870.62705118949
but 2870.6270511894882
; just compare the values:
2870.6270511894882 Actual
2870.6270511894881565 You want to have
2870.62705118949 Proposed by changing 8A into 8E
and see that "8A 7F DA 0C 41 6D A6 40" is, in fact, a better choice (more accurate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With