Reputation: 638
I'm running into a strange java bug using the intValue() from the BigDecimal class.
I'm starting with a value of 3300028000.
When I call the following code:
int i = d.intValue();
it returns: -994939296
Any ides as to why this would happen?
Upvotes: 3
Views: 4889
Reputation: 2579
I don't know why you need the int value of a BigDecimal but the class BigDecimal contains lots of methods to fit your request.
compareTo
add
substract
multiply
divide
etc..
I would work with BigDecimal itself. Sooner or later; Converting the BigDecimal type to other primitive types will end up with an error. Cuz all of them has a limit.
Upvotes: 0
Reputation: 28752
What would you like it to return? :)
As described in the javadocs:
if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned
intValueExact, on the other hand, would throw an exception.
Upvotes: 2
Reputation: 17444
You should really read Java API before blaming it:
Converts this BigDecimal to an int. This conversion is analogous to the narrowing primitive conversion from double to short as defined in section 5.1.3 of 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.
Upvotes: 1
Reputation: 821
When you try to fit this number into an int variable, it overflows, since the int type in Java has 32 bits, ergo an int variable can store values that range from −2,147,483,648 to 2,147,483,647.
To store the value of your BigInteger, you have to use a long variable. Try this:
long value = d.longValue();
Upvotes: 3
Reputation: 1157
An int can't hold a value that big, so it overflows. Try using a long.
Upvotes: 4