我声明了一个包含 4 个字节的字节数组。
byte[] bts = new byte[] { 0xff, 0xff, 0x7f, 0x7f };
float f1 = BitConverter.ToSingle(bts, 0);
string s = f1.ToString();
float f2 = float.Parse(s);
byte[] bts2 = BitConverter.GetBytes(f2);
经过一些转换,我意识到输出发生了变化
{ 0xff, 0xff, 0x7f, 0x7f }
至
{ 0xfD, 0xff, 0x7f, 0x7f }
为什么会发生这种情况?
最佳答案
如果您在监 window 口中查看 f1
和 f1.ToString()
,您会看到
f1
= 3.40282347E+38
f1.ToString()
= 3.402823E+38
这意味着 ToString
方法输出表示修剪数字的 string
,并且不如 4 字节 float
准确,但是为什么呢?
默认float.ToString
使用The G
specifier in the standard numeric format strings
float
的精度为 7 位。
您可以使用other overload of ToString
指定格式说明符并为其提供要表示的位数:
string s = f1.ToString("G10");
更好的方法是使用无损的“R”
说明符
string s = f1.ToString("R");
MSDN: The round-trip ("R") format specifier is used to ensure that a numeric value that is converted to a string will be parsed back into the same numeric value.
关于C# float max 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199788/