如果传入的数据有很多位,那么使用double会导致精度丢失,这个时候就要用bigdecimal来进行转换。
实例:
public class checkstrisnum { public static void main(string[] args) { double aa = -192322.1212; string a = "-192322.1212"; string b = "-192322a1212"; string c = "java"; string d = "5"; /** 判断是否全为数字 */ system.out.println(checkstrisnum02(double.tostring(aa))); system.out.println(checkstrisnum02(a)); system.out.println(checkstrisnum02(b)); system.out.println(checkstrisnum02(c)); system.out.println(checkstrisnum02(d)); } private static pattern number_pattern = pattern.compile("-?[0-9]+(\\.[0-9]+)?"); /** * 利用正则表达式来判断字符串是否为数字 */ public static boolean checkstrisnum02(string str) { string bigstr; try { /** 先将str转成bigdecimal,然后在转成string */ bigstr = new bigdecimal(str).tostring(); } catch (exception e) { /** 如果转换数字失败,说明该str并非全部为数字 */ return false; } matcher isnum = number_pattern.matcher(str); if (!isnum.matches()) { return false; } return true; } }
推荐教程:java开发入门
以上就是java使用正则表达式判断传入数据是否为数字的详细内容。
