Search code examples
javabigdecimal

BigDecimal.intValue() returns Unexpected Number


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?


Solution

  • 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();