Check if user input ending in the alphabet "F" is entered

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

I use the instructions below for this purpose,

Double.parseDouble(string); 

It works in most scenarios but does not work when user input 123f

This should be considered as a string, however the above case treats it as a number. I even tried to use

  NumberUtils.isNumber(string); 

but still the behavior is the same.

I tried the following regex pattern that works

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

However, is there any other alternative api for it.

+4
source share
3 answers

Check out the rather complex regex specified in the documentation for Double.valueOf . If you need to be more restrictive for your application, you will need to write your own regular expression. As others have pointed out, using Double.parseDouble allows a lot, including Infinity .

+1
source

From doc

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

Thus, 123F is represented as a hexadecimal number.

Instead, you can use the NumberUtils.isDigits(String s) method

it checks if the string contains only numbers.

So your working code might look like

 boolean b = NumberUtils.isDigits(string); if(!b) // then all are digits 
0
source

If I were going to support the floating point suffix F, I would 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 would recommend that you do not allow this.

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

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


However, is there any other alternative api for it.

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

0
source

Source: https://habr.com/ru/post/1489478/


All Articles