java判断数字(整型,浮点)---正则表达式

java判断数字(整型,浮点)---正则表达式

//浮点型判断
 public static boolean isDecimal(String str) {
  if(str==null || "".equals(str))
   return false;  
  Pattern pattern = Pattern.compile("[0-9]*(\\.?)[0-9]*");
  return pattern.matcher(str).matches();
 }

 //整型判断
 public static boolean isInteger(String str){
  if(str==null )
   return false;
  Pattern pattern = Pattern.compile("[0-9]+");
  return pattern.matcher(str).matches();
 }

浮点型测试用例:
 public void testIsDecimal() {
  
  assertTrue("123",Test.isDecimal("1"));
  assertTrue("12.3",Test.isDecimal("12.3"));
  assertTrue(".123",Test.isDecimal(".123"));
  assertTrue("123.",Test.isDecimal("123."));
  
  assertFalse("",Test.isDecimal(""));
  assertFalse("null",Test.isDecimal(null));
  assertFalse("abc", Test.isDecimal("abc"));
  assertFalse("123abc", Test.isDecimal("123abc"));
  assertFalse("abc123", Test.isDecimal("abc123"));
  assertFalse("123.2.2", Test.isDecimal("123.2.2"));
  
 }
到google中找了下java判断数字的资料有点不全(没有浮点的判断),发现有的还有错误。所有自己就弄了一个做为笔记以后用。
可能自己的也有点测试不到位,但是我想到的测试用例,都测试通过。

你可能感兴趣的:(java判断数字(整型,浮点)---正则表达式)