java - Validating int and float value all together -


i getting value named amount in object through getter shown below.

let's object h then

h.getamount() 

now need develop validator validate amount should of type integer , if not throw exception, have developed shown below

private  boolean isint (string amount){     boolean isvalid = true;     try {         integer.parseint(amount);      }     catch(numberformatexception e){         isvalid = false;     }      return isvalid; } 

now issue amount coming h integer such 1234, can float such 1258.26. in case of float throws numberformatexception.

how make perfect both values whether integer or whether float?

you use regex this:-

if (str.matches("[-+]?[0-9]*\\.?[0-9]+")) { // can use `\\d` instead of `0-9` too!     // number - int, float, double          } 

[-+]? - sign.

[0-9]*\.?[0-9]+ - numbers , decimal point between them.

update:-

in case exponential needs handled too, below regex can used.

string regex = "[-+]?[0-9]*\\.?[0-9]+([ee][-+]?[0-9]+)?"; 

Comments