views:

93

answers:

6

Hi, I have Hibernate method which returns me a BigDecimal. I have another API method to which I need to pass that number but it accepts Integer as parameter. I cannot change return types or variable types of both methods.

Now how to convert the BigDecimal into Integer and pass it to second method?

Is there a way out of this?

+5  A: 

Can you guarantee that the BigDecimal will never contain a value larger than Integer.MAX_VALUE?

If yes, then here's your code:

Integer.valueOf(bdValue.intValue())
Anon
Yes. I guess it will not contain larger value than Integer.MAX_VALUE
psvm
A: 

See BigDecimal#intValue()

Kevin
A: 

Following should do the trick:

BigDecimal d = new BigDecimal(10);
int i = d.intValue();
Gareth Davis
+3  A: 

Well, you could call BigDecimal.intValue():

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

You can then either explicitly call Integer.valueOf(int) or let auto-boxing do it for you if you're using a sufficiently recent version of Java.

Jon Skeet
I'm putting 'getting more up votes than Jon Skeet' on my CV
willcodejavaforfood
+8  A: 

You would call myBigDecimal.intValueExact() (or just intValue()) and it will even throw an exception if you would lose information. That returns an int but autoboxing takes care of that.

willcodejavaforfood
`intValueExact()` is a good recommendation; it was added in 1.5
Anon
A: 

Have you tried calling BigInteger#intValue() ?

Riduidel