java number exceeds long.max_value - how to detect?
Posted
by
jurchiks
on Stack Overflow
See other posts from Stack Overflow
or by jurchiks
Published on 2012-09-10T08:42:54Z
Indexed on
2012/09/10
9:38 UTC
Read the original article
Hit count: 220
I'm having problems detecting if a sum/multiplication of two numbers exceeds the maximum value of a long integer.
Example code:
long a = 2 * Long.MAX_VALUE;
System.out.println("long.max * smth > long.max... or is it? a=" + a);
This gives me -2
, while I would expect it to throw a NumberFormatException
...
Is there a simple way of making this work? Because I have some code that does multiplications in nested IF blocks or additions in a loop and I would hate to add more IFs to each IF or inside the loop.
Edit: oh well, it seems that this answer from another question is the most appropriate for what I need: http://stackoverflow.com/a/9057367/540394
I don't want to do boxing/unboxing as it adds unnecassary overhead, and this way is very short, which is a huge plus to me. I'll just write two short functions to do these checks and return the min or max long.
Edit2: here's the function for limiting a long to its min/max value according to the answer I linked to above:
/**
* @param a : one of the two numbers added/multiplied
* @param b : the other of the two numbers
* @param c : the result of the addition/multiplication
* @return the minimum or maximum value of a long integer if addition/multiplication of a and b is less than Long.MIN_VALUE or more than Long.MAX_VALUE
*/
public static long limitLong(long a, long b, long c)
{
return (((a > 0) && (b > 0) && (c <= 0))
? Long.MAX_VALUE
: (((a < 0) && (b < 0) && (c >= 0)) ? Long.MIN_VALUE : c));
}
Tell me if you think this is wrong.
© Stack Overflow or respective owner