Best implementation for an isNumber(string) method

前端 未结 19 2530
感动是毒
感动是毒 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:19

    I just ran some benchmarks on the performance of these 2 methods (On Macbook Pro OSX Leopard Java 6). ParseInt is faster. Here is the output:

    This operation took 1562 ms.
    This operation took 2251 ms.
    

    And here is my benchmark code:

    
    public class IsIntegerPerformanceTest {
    
        public static boolean isIntegerParseInt(String str) {
            try {
                Integer.parseInt(str);
                return true;
            } catch (NumberFormatException nfe) {}
            return false;
        }
    
        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

    Also, note that your regex will reject negative numbers and the parseInt method will accept them.

提交回复
热议问题