[英]c# convert bytes to double with a “higher” precision
I always convert bytes to double with System.BitConverter.ToDouble()
like this: 我总是使用
System.BitConverter.ToDouble()
将字节转换为两倍,如下所示:
double value = BitConverter.ToDouble(flt, 0);//flt is an array of bytes.
But when I try to convert "8 A 7F DA 0C 41 6D A6 40"(Little Endian),it become 2870.62705118949
. 但是,当我尝试转换“ 8 A 7F DA 0C 41 6D A6 40”(Little Endian)时,它变成
2870.62705118949
。
Indeed, 2870.62705118949
is "8 E 7F DA 0C 41 6D A6 40". 实际上,
2870.62705118949
是“ 8 E 7F DA 0C 41 6D A6 40”。
But what I want is 2870.6270511894881565
.How can I get the accurate value using C#? 但是我想要的是
2870.6270511894881565
如何使用C#获得准确的值?
When working with exact string representation , use "R" formatting: 使用精确的字符串表示形式时 ,请使用“ R”格式:
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/dwhawy9k(v=vs.110).aspx
"R" or "r" Round-trip Result: A string that can round-trip to an identical number.
“ R”或“ r”往返结果:可以往返到相同数字的字符串。
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
; 如您所见,实际值不是
2870.62705118949
而是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 "8 A 7F DA 0C 41 6D A6 40" is, in fact, a better choice ( more accurate ) 并且看到“ 8 A 7F DA 0C 41 6D A6 40”实际上是一个更好的选择( 更准确 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.