apache commons lang - Convert any number string(int, float, double, long, etc) to appropriate numeric (int, float, double, long, etc) value in java -



apache commons lang - Convert any number string(int, float, double, long, etc) to appropriate numeric (int, float, double, long, etc) value in java -

is there improve practice convert input number string (int, double, etc) it's respective wrapper object/primitive type in java?

using valueof() or parsexxx() methods can achieved. should knowing underlying string format before selecting appropriate type.

what doing parsing number string long, using numberutils commons-lang.jar follows:

long longvalue= (long) numberutils.tolong(numberstring);

but problem if numberstring has double value, fails parse number , homecoming 0.0 parsed value. next statement works fine double values :

long longvalue = (long) numberutils.todouble(numberstring);

is there generic way of doing this? don't care digits after decimal.

thanks reading.

update

this looks elegant solution me, suggested @thomas :

numberformat numberformat = numberformat.getnumberinstance(); long longvalue = numberformat.parse(targetfieldvalue).longvalue();

as parse() method returns long or double wrapper object, can checked , assigned accordingly generic use. grab here parse() throw parseexception, need handled according requirement.

i've used solve problem, curious know other solutions!!

import static org.apache.commons.lang3.math.numberutils.isdigits; import static org.apache.commons.lang3.math.numberutils.todouble; import static org.apache.commons.lang3.math.numberutils.tolong; public static void main(string[] args) { string numberstring = "-23.56"; long longnumber = (isdigits(numberstring) ? tolong(numberstring) : (long) todouble(numberstring)); system.out.println(longnumber); }

the cast here assumes happy truncating decimal, regardless of sign (the presence of - in string mean isdigits returns false). if not, appropriate rounding.

if fear string might contain alphabets, utilize createlong variant throw numberformatexception instead of defaulting 0.

java apache-commons-lang

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -