5

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]);
}

3 Answers 3

12

You can get pretty far with Number:

Long l = ((Number) object).longValue();
Integer i = ((Number) object).intValue();
Sign up to request clarification or add additional context in comments.

Comments

3

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?

Comments

0

The java.lang.Number class and related classes do most of this job just fine. If you need more support for handling nulls and primitives without writing checks and conditionals, check out the Apache Commons-Lang libraries, specifically NumberUtil.class. These are mature, commonly used, and well-documented libraries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.