java - Check if number is too large or not a number -


i trying parse string safely,

public <t> long safeparselong(t s){     try {         return long.parselong(s.tostring());     }catch (numberformatexception e){         return 0;     } } 

this work , if string not parsable, return 0.

however, there way know reason unparsable? specifically, want know if not number @ ("foo") or number large (≥ 9223372036854775808).

the long.parselong method throw numberformatexception if string isn't number or if number wouldn't fit in long.

if exception thrown, test whether string fits regular expression number, "[+-]?[0-9]+". if matches, it's number couldn't fit in long. if doesn't match, wasn't number @ all, e.g. "foo".

boolean isnumber = s.tostring().matches("[+-]?[0-9]+"); 

but returning 0 if there error. indistinguishable if content of string "0". perhaps better let exception thrown method. instead of numberformatexception, create , throw notanumberexception if it's not numeric string, or numbermagnitudetoolargeexception if parsing failed because it's large fit in long.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -