4

I need to check if the user input is a string or a number.

I use the below statement for the purpose,

Double.parseDouble(string);

It works in most of the scenarios, but fails when the input entered by the user is like 123F

This should be considered as a string however the above case considers it as a number. I even tried using

 NumberUtils.isNumber(string);

but still the behaviour is same.

I tried the following regex pattern which works

"-?\\d+(\\.\\d+)?"

However is there any other alternate api for the same.

Thor
  • 6,607
  • 13
  • 62
  • 96
Anand B
  • 2,997
  • 11
  • 34
  • 55

3 Answers3

1

Check out the rather complicated regular expression that is listed in the documentation for Double.valueOf. If you need to be more restrictive for your application, you will need to write your own regex. As others pointed out, using Double.parseDouble allows many things, including Infinity.

K Boden
  • 626
  • 4
  • 6
0

From the doc

Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).

So the 123F seems to be detected as a hex number.

You can use NumberUtils.isDigits(String s) method instead

it checks whether the String contains only digit characters.

So your working code can be look like

boolean b = NumberUtils.isDigits(string);
if(!b)
  // then all are digits
stinepike
  • 54,068
  • 14
  • 92
  • 112
0

If I was going to support floating point numbers with an F suffix, I'd do it like this:

if (str.endsWith("F") || str.endsWith("f")) {
   num = Double.parseDouble(str.substring(0, str.length() - 1));
} else {
   num = Double.parseDouble(str);
} 

However, I'd recommend that you don't allow this.

The "f" suffix is not a standard mathematical / scientific form. It only has a well defined meaning in certain programming languages ... as numeric literal in the source code of a program. In that context, it denotes a floating point number with an IEE single precision representation. (And you are trying to treat it as a double!)

The best way to avoid this potential confusion (for a small subset programmers who don't grok the difference between a number and a numeric literal) is to simply treat it as bad input.


However is there any other alternate api for the same.

AFAIK, no. Mainly because the format doesn't really make sense.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216