Best implementation for an isNumber(string) method

前端 未结 19 2369
感动是毒
感动是毒 2020-12-15 20:04

In my limited experience, I\'ve been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea h

相关标签:
19条回答
  • 2020-12-15 20:21

    I use this but I liked Asaph's rigor in his post.

    public static bool IsNumeric(object expression)
    {
    if (expression == null)
    return false;
    
    double number;
    return Double.TryParse(Convert.ToString(expression, CultureInfo.InvariantCulture),   NumberStyles.Any,
    NumberFormatInfo.InvariantInfo, out number);
    }
    
    0 讨论(0)
  • 2020-12-15 20:21
     public static boolean isNumber(String str){
          return str.matches("[0-9]*\\.[0-9]+");
        }
    

    to check whether number (including float, integer) or not

    0 讨论(0)
  • 2020-12-15 20:28

    I like code:

    public static boolean isIntegerRegex(String str) {
        return str.matches("^[0-9]+$");
    }
    

    But it will good more when create Pattern before use it:

    public static Pattern patternInteger = Pattern.compile("^[0-9]+$");
    public static boolean isIntegerRegex(String str) {
      return patternInteger.matcher(str).matches();
    }
    

    Apply by test we have result:

    This operation isIntegerParseInt took 1313 ms.
    This operation isIntegerRegex took 1178 ms.
    This operation isIntegerRegexNew took 304 ms.
    

    With:

    public class IsIntegerPerformanceTest {
      private static Pattern pattern = Pattern.compile("^[0-9]+$");
    
        public static boolean isIntegerParseInt(String str) {
        try {
          Integer.parseInt(str);
          return true;
        } catch (NumberFormatException nfe) {
        }
        return false;
      }
    
      public static boolean isIntegerRegexNew(String str) {
        return pattern.matcher(str).matches();
      }
    
      public static boolean isIntegerRegex(String str) {
        return str.matches("^[0-9]+$");
      }
    
        public static void main(String[] args) {
            long starttime, endtime;
        int iterations = 1000000;
        starttime = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
          isIntegerParseInt("123");
          isIntegerParseInt("not an int");
          isIntegerParseInt("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation isIntegerParseInt took " + (endtime - starttime) + " ms.");
        starttime = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
          isIntegerRegex("123");
          isIntegerRegex("not an int");
          isIntegerRegex("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation took isIntegerRegex " + (endtime - starttime) + " ms.");
        starttime = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
          isIntegerRegexNew("123");
          isIntegerRegexNew("not an int");
          isIntegerRegexNew("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation took isIntegerRegexNew " + (endtime - starttime) + " ms.");
      }
    }
    
    0 讨论(0)
  • 2020-12-15 20:29

    You could create an extension method for a string, and make the whole process look cleaner...

    public static bool IsInt(this string str)
    {
        int i;
        return int.TryParse(str, out i);
    }
    

    You could then do the following in your actual code...

    if(myString.IsInt())....
    
    0 讨论(0)
  • 2020-12-15 20:29

    I think people here is missing a point. The use of the same pattern repeatedly has a very easy optimization. Just use a singleton of the pattern. Doing it, in all my tests the try-catch approach never have a better benchmark than the pattern approach. With a success test try-catch takes twice the time, with a fail test it's 6 times slower.

    public static final Pattern INT_PATTERN= Pattern.compile("^-?[0-9]+(\\.[0-9]+)?$");
    
    public static boolean isInt(String s){
      return INT_PATTERN.matcher(s).matches();
    }
    
    0 讨论(0)
  • 2020-12-15 20:30

    public static boolean CheckIfNumber(String number){

        for(int i = 0; i < number.length(); i++){
            try{
                Double.parseDouble(number.substring(i));
    
            }catch(NumberFormatException ex){
                return false;
            }
        }
        return true;     
    }
    

    I had this problem before but when I had input a number and then a character, it would still return true, I think this is the better way to do it. Just check if every char is a number. A little longer but it takes care if you have the situation of a user inputting "1abc". For some reason, when I tried to try and catch without iterating, it still thought it was a number so..

    0 讨论(0)
提交回复
热议问题