Determine if a String is a number and convert in Java?

Michael McGowan picture Michael McGowan · May 4, 2011 · Viewed 16.3k times · Source

I know variants of this question have been asked frequently before (see here and here for instance), but this is not an exact duplicate of those.

I would like to check if a String is a number, and if so I would like to store it as a double. There are several ways to do this, but all of them seem inappropriate for my purposes.

One solution would be to use Double.parseDouble(s) or similarly new BigDecimal(s). However, those solutions don't work if there are commas present (so "1,234" would cause an exception). I could of course strip out all commas before using these techniques, but that would seem to pose loads of problems in other locales.

I looked at Apache Commons NumberUtils.isNumber(s), but that suffers from the same comma issue.

I considered NumberFormat or DecimalFormat, but those seemed far too lenient. For instance, "1A" is formatted to "1" instead of indicating that it's not a number. Furthermore, something like "127.0.0.1" will be counted as the number 127 instead of indicating that it's not a number.

I feel like my requirements aren't so exotic that I'm the first to do this, but none of the solutions does exactly what I need. I suppose even I don't know exactly what I need (otherwise I could write my own parser), but I know the above solutions do not work for the reasons indicated. Does any solution exist, or do I need to figure out precisely what I need and write my own code for it?

Answer

Giulio Piancastelli picture Giulio Piancastelli · Feb 8, 2012

Sounds quite weird, but I would try to follow this answer and use java.util.Scanner.

Scanner scanner = new Scanner(input);
if (scanner.hasNextInt())
    System.out.println(scanner.nextInt());
else if (scanner.hasNextDouble())
    System.out.println(scanner.nextDouble());
else
    System.out.println("Not a number");

For inputs such as 1A, 127.0.0.1, 1,234, 6.02e-23 I get the following output:

Not a number
Not a number
1234
6.02E-23

Scanner.useLocale can be used to change to the desired locale.