Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
Mike Avatar asked Dec 05 '25 02:12

Mike


2 Answers

An int can't hold a value that big, so it overflows. Try using a long.

like image 145
Alexander Corwin Avatar answered Dec 07 '25 18:12

Alexander Corwin


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();
like image 36
Tiago Pasqualini Avatar answered Dec 07 '25 18:12

Tiago Pasqualini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!