Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java library for converting Object to numeric (Integer, Long etc..)

I need to convert array of Objects into a Long/Integer.. Problem is that those Objects are sometimes BigIntegers, sometimes BigDecimals and sometimes even something else. Is there any good libraries for accomplishing this?

for example...

for (Object[] o : result) {
    Long l = SomeClass.convertToLong(o[0]);
    Integer i = SomeClass.convertToInt(o[1]);
}
like image 554
vrm Avatar asked Feb 19 '10 12:02

vrm


2 Answers

You can get pretty far with Number:

Long l = ((Number) object).longValue();
Integer i = ((Number) object).intValue();
like image 103
Joonas Pulakka Avatar answered Nov 03 '22 01:11

Joonas Pulakka


For the case of BigInteger and BigDecimal you can just cast that (and all numeric primitive wrapper classes as well) to Number and get the longValue() (be careful when overflowing the range of long 'though).

If they are something else, then you'd need some rules on how to convert it anyway. What "something else" do you have in mind?

like image 32
Joachim Sauer Avatar answered Nov 02 '22 23:11

Joachim Sauer