Regex or Exception Handling?

前端 未结 7 1900
暗喜
暗喜 2021-01-13 06:22

Which one of the following is a better practice to check if a string is float?

try{
 Double.parseDouble(strVal);
}catch(NumberFormatException e){
 //My Logic         


        
7条回答
  •  礼貌的吻别
    2021-01-13 06:26

    May be you can also try this way.But this is generic for a string containing valid number.

    public static boolean isNumeric(String str) 
    { 
        str = "2.3452342323423424E8";
     //   str = "21414124.12412412412412";
     //   str = "123123";
        NumberFormat formatter = NumberFormat.getInstance(); 
        ParsePosition pos = new ParsePosition(0); 
        formatter.parse(str, pos); 
        return  str.length() == pos.getIndex();  
    }
    

提交回复
热议问题