加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么C#TryParse不能处理NaN?

发布时间:2020-12-16 10:35:51 所属栏目:百科 来源:网络整理
导读:在读取一些旧的Fortran数据时,我有一些常用的方法可以使用默认值覆盖进行解析.有时,数据的NaN(非数字)应该有一个数值.我预计TryParse会看到字符串“NaN”并且无法解析.但是,TryParse成功解析并将NaN放入数值.这是预期的行为吗?如果这是预期的,我还应该寻找
在读取一些旧的Fortran数据时,我有一些常用的方法可以使用默认值覆盖进行解析.有时,数据的NaN(非数字)应该有一个数值.我预计TryParse会看到字符串“NaN”并且无法解析.但是,TryParse成功解析并将NaN放入数值.这是预期的行为吗?如果这是预期的,我还应该寻找其他任何“陷阱”值吗?

public static double GetDoubleFromString(string s,double defaultOnFailure = 0)
    {
        //Must be here due to TryParse returning NaN to d and result is set to true below
        if (s.Contains("NaN"))
        {
            log.Warn(string.Format("String contained NaN,returning defaultOnFailure {0} string was {1}",defaultOnFailure,s));
            return defaultOnFailure;
        }

        var d = defaultOnFailure;
        if (!double.TryParse(s.Trim(),out d))
        {
            log.Warn(string.Format("Failed to parse double from string returning defaultOnFailure {0} string was {1}",s));
        }

        return d;
    }

UPDATE

我觉得应该提到,这只发生在double,long和int不返回NaN值.请参阅下面的示例代码,Common ….代码只是格式化的Console.WriteLine或停止执行控制台.请参阅下面的截图输出.

public static void NanTestMain()
    {
        Common.WriteBlankWithTitle("Test parse NaN");
        string s = "NaN";

        Common.WriteBlankWithTitle("NaN to Int");
        int i;
        var intSuccess = int.TryParse(s,out i);
        Console.WriteLine(string.Format("Int parse of {0} parse = {1}",i,intSuccess));

        Common.WriteBlankWithTitle("NaN to Double");
        double d;
        var doubleSuccess = double.TryParse(s,out d);
        Console.WriteLine(string.Format("Double parse of {0} parse = {1}",d,doubleSuccess));

        Common.WriteBlankWithTitle("NaN to Long");
        long l;
        var longSuccess = long.TryParse(s,out l);
        Console.WriteLine(string.Format("Long parse of {0} parse = {1}",l,longSuccess));

        Common.Pause();
    }

Results of Update Code

解决方法

从 MSDN开始:

The s parameter can contain 07001,07002,or 07003 for the culture indicated by provider.

有三个“特殊”值需要注意.然而,最后几个字是关键 – 根据当前的文化,你可能会看到“NaN”以外的东西!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读