C# float max 解析错误

标签 c# .net floating-point formatting tostring

我声明了一个包含 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 口中查看 f1f1.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/

相关文章:

javascript - 无法调用 Blazor javascript 方法

.net - 揭开依赖属性的神秘面纱

c# - 在C#中将字符串转换为json数组

java - 绘制: Use floating point vs.整数的坐标?

c# - 我什么时候应该使用 double 而不是十进制?

c# - 为什么这个方法会导致Code Analysis error CA2000 : Call Dispose()

c# - 在 Windows Mobile 中如何使应用程序在设备启动时启动?

javascript - 防止浏览器控制从特定域加载 javascript

c# - c#.net 中委托(delegate)事件的 super 简单示例?

c++ - 应用于浮点值时,std::abs 和 std::fabs 之间有什么区别吗?