【问题标题】:C# float max parse errorC# float max 解析错误
【发布时间】:2017-01-05 02:28:47
【问题描述】:

我声明了一个包含 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 }

为什么会这样?

【问题讨论】:

  • 欢迎来到 StackOverflow!请澄清您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。

标签: c# .net floating-point formatting tostring


【解决方案1】:

如果您在监视窗口中查看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 stringsfloats 的精度为 7 位。

您可以使用other overload of ToString 指定格式说明符并为其提供您要表示的位数:

string s = f1.ToString("G10");

更好的方法是使用无损的"R" 说明符

string s = f1.ToString("R");

MSDN:往返 ("R") 格式说明符用于确保转换为字符串的数值将被解析回相同的数值。

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 2022-08-02
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多