Is there a better practice to convert any input number string (int, double, etc) to it's respective Wrapper object/primitive type in java?
Using valueOf()
or parseXXX()
methods it can achieved. but I should be knowing the underlying string format before selecting the appropriate type.
What I am doing is parsing number string to long, using the NumberUtils
from commons-lang.jar as follows:
long longValue= (long) NumberUtils.toLong(numberString);
but the problem is If the numberString
has a double
value, then it fails to parse to number and will return 0.0
as parsed value. Only the following statement works fine for double values :
Long longValue = (long) NumberUtils.toDouble(numberString);
Is there a generic way of doing this? also I don't care about the digits after the decimal.
Thanks for reading.
Update
This looks elegant solution to me, suggested by @Thomas :
NumberFormat numberFormat = NumberFormat.getNumberInstance();
long longValue = numberFormat.parse(targetFieldValue).longValue();
as the parse()
method returns Long
or Double
wrapper object, It can be checked and assigned accordingly for generic use. Only catch here is that the parse()
could throw ParseException
, so need to be handled according to the requirement.
I've used this to solve my problem, but curious to know about any other solutions!!
The cast here assumes that you are happy with truncating the decimal, regardless of the
sign
(the presence of-
in the string would meanisDigits
returnsfalse
). If not, do the appropriate rounding.If you fear the string might contain alphabets, use the
createLong
variant that would throw aNumberFormatException
instead of defaulting to0
.