您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java判断字符串是不是数字的方法

2024/3/22 3:22:44发布28次查看
用java自带的函数
    public static boolean isnumericzidai(string str) {        for (int i = 0; i < str.length(); i++) {            system.out.println(str.charat(i));            if (!character.isdigit(str.charat(i))) {                return false;            }        }        return true;    }
其中character.isdigit方法:确定或判断指定字符是否是一个数字。
测试方法:
    public static void main(string[] args) {        double aa = -19162431.1254;        string a = -19162431.1254;        string b = -19162431a1254;        string c = 中文;        system.out.println(isnumericzidai(double.tostring(aa)));        system.out.println(isnumericzidai(a));        system.out.println(isnumericzidai(b));        system.out.println(isnumericzidai(c));    }
结果显示:
falsefalsefalsefalse
这种方法显然不能判断 负数。
用正则表达式
    /**     * 匹配是否为数字     * @param str 可能为中文,也可能是-19162431.1254,不使用bigdecimal的话,变成-1.91624311254e7     * @return     * @date 2016年11月14日下午7:41:22     */    public static boolean isnumeric(string str) {        // 该正则表达式可以匹配所有的数字 包括负数        pattern pattern = pattern.compile(-?[0-9]+(\\.[0-9]+)?);        string bigstr;        try {            bigstr = new bigdecimal(str).tostring();        } catch (exception e) {            return false;//异常 说明包含非数字。        }        matcher isnum = pattern.matcher(bigstr); // matcher是全匹配        if (!isnum.matches()) {            return false;        }        return true;    }
使用org.apache.commons.lang
public static boolean isnumeric(string str)checks if the string contains only unicode digits. a decimal point is not a unicode digit and returns false.null will return false. an empty string () will return true. stringutils.isnumeric(null)   = false stringutils.isnumeric()     = true stringutils.isnumeric(  )   = false stringutils.isnumeric(123)  = true stringutils.isnumeric(12 3) = false stringutils.isnumeric(ab2c) = false stringutils.isnumeric(12-3) = false stringutils.isnumeric(12.3) = falseparameters:str - the string to check, may be null returns:true if only contains digits, and is non-null
更多java知识请关注java基础教程。
以上就是java判断字符串是不是数字的方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product