Most elegant way to detect if a String is a number?

前端 未结 11 805

Is there a better, more elegant (and/or possibly faster) way than

boolean isNumber = false;
try{
   Double.valueOf(myNumber);
   isNumber = true;
} catch (Nu         


        
11条回答
  •  攒了一身酷
    2020-12-30 12:04

    You could use a regex, i.e. something like String.matches("^[\\d\\-\\.]+$"); (if you're not testing for negative numbers or floating point numbers you could simplify a bit).

    Not sure whether that would be faster than the method you outlined though.

    Edit: in the light of all this controversy, I decided to make a test and get some data about how fast each of these methods were. Not so much the correctness, but just how quickly they ran.

    You can read about my results on my blog. (Hint: Jon Skeet FTW).

提交回复
热议问题