Nexus
Nexus

Reputation: 821

How to get an integer value that is greater than the maximum integer value

I know that in Java an int can get a value of 2,147,483,647. But I want more value than that. I have a formula for example:

double x = a/(b*c); 

So the denominator (b*c) can reach to 10^10 or maybe even higher than that. But whenever I execute the formula, the value is always limited to 2,147,483,647. I know because x must always be smaller than 1.0. P/S: Even variable "a" can also reach 10^10 if some conditions are satisfied. a,b,c are all integer numbers.

Upvotes: 7

Views: 55396

Answers (4)

Steve P.
Steve P.

Reputation: 14699

Since you asked for it, here's a BigInteger example:

BigInteger a = new BigInteger("yourNumberInStringFormA");
BigInteger b = new BigInteger("yourNumberInStringFormB");
BigInteger c = new BigInteger("yourNumberInStringFormC");

BigInteger x = a.divide(b.multiply(c));

Where "yourNumberInStringForm" is an optional minus sign and numbers only (no whitespace or commas). For example BigInteger z = new BigIntger("-3463634"); NB: BigInteger will actually return a long for you if your number is in its range. longs end in L, as in:

long num = 372036854775807L;

The max length for a long is: 9,223,372,036,854,775,807. If your numbers are going to be less than that, it'll make your life a ton easier to use long or Long, its wrapper, over BigInteger. Since with long, you don't have to use methods for dividing/multiplying, etc.

Upvotes: 6

djeikyb
djeikyb

Reputation: 4588

The max int value is a java language constant. If you want real numbers larger than what int provides, use long. If you need integers larger than what int and long provide, you can use BigInteger:

BigInteger a = new BigInteger("9");
BigInteger b = new BigInteger("3");
BigInteger c = a.add(b); // c.equals(new BigInteger("12"), a and b are unchanged

BigInteger is immutable just like Long and Integer, but you can't use the usual operator symbols. Instead use the methods provided by the class.

I also notice you're ending up with a double. If it's okay to use doubles throughout your formula, it's worth noting that their max value is: 1.7976931348623157 E 308

Read more about java language constants.

Upvotes: 4

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

double x = a / ((double) b * c);

a and c will be cast to double by java automatically. See http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2 If either operand is of type double, the other is converted to double.

Upvotes: 0

morgano
morgano

Reputation: 17422

Use a long type, still an integer type but its maximum value is higher than int

Upvotes: 2

Related Questions