检测String是否为数字的最优雅方法? [英] Most elegant way to detect if a String is a number?

查看:239
本文介绍了检测String是否为数字的最优雅方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比

boolean isNumber = false;
try{
   Double.valueOf(myNumber);
   isNumber = true;
} catch (NumberFormatException e) {
}

...?

编辑
因为我不能选择两个答案我要去与正则表达式一样,因为a)它优雅而且b)说Jon Skeet解决问题是一个重言式,因为Jon Skeet本身就是所有问题的解决方案。

Edit: Since I can't pick two answers I'm going with the regex one because a) it's elegant and b) saying "Jon Skeet solved the problem" is a tautology because Jon Skeet himself is the solution to all problems.

推荐答案

我不相信Java中有任何内容可以更快,更可靠地执行它,假设稍后您将要使用Double.valueOf(或类似)实际解析它。

I don't believe there's anything built into Java to do it faster and still reliably, assuming that later on you'll want to actually parse it with Double.valueOf (or similar).

我使用Double.parseDouble而不是Double.valueOf来避免不必要地创建Double,你也可以更快地摆脱肆无忌惮的愚蠢数字通过检查数字,e / E, - 和。预先。所以,例如:

I'd use Double.parseDouble instead of Double.valueOf to avoid creating a Double unnecessarily, and you can also get rid of blatantly silly numbers quicker than the exception will by checking for digits, e/E, - and . beforehand. So, something like:

public boolean isDouble(String value)
{        
    boolean seenDot = false;
    boolean seenExp = false;
    boolean justSeenExp = false;
    boolean seenDigit = false;
    for (int i=0; i < value.length(); i++)
    {
        char c = value.charAt(i);
        if (c >= '0' && c <= '9')
        {
            seenDigit = true;
            continue;
        }
        if ((c == '-' || c=='+') && (i == 0 || justSeenExp))
        {
            continue;
        }
        if (c == '.' && !seenDot)
        {
            seenDot = true;
            continue;
        }
        justSeenExp = false;
        if ((c == 'e' || c == 'E') && !seenExp)
        {
            seenExp = true;
            justSeenExp = true;
            continue;
        }
        return false;
    }
    if (!seenDigit)
    {
        return false;
    }
    try
    {
        Double.parseDouble(value);
        return true;
    }
    catch (NumberFormatException e)
    {
        return false;
    }
}

请注意,尽管尝试了几次,但仍然不包括NaN或十六进制值。是否希望这些传递取决于上下文。

Note that despite taking a couple of tries, this still doesn't cover "NaN" or hex values. Whether you want those to pass or not depends on context.

根据我的经验,正则表达式比上面的硬编码检查要慢。

In my experience regular expressions are slower than the hard-coded check above.

这篇关于检测String是否为数字的最优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆