views:

14

answers:

2

Hi

I am building a unit convertor program that uses the MathFP library. Typically unit conversion occurs in the formula of:

U1 (unit1) * K (constant) = U2 (unit2)

I want to be able to detect when the an int has over/underflowed? How can I detect when this has occured and gracefully handle the problem. Ideally I would be looking for a generic solution, as I would want to handle overflow with primitives of type long:

The only idea I have is:

int largeOne = bigNum;
int largeTwo = anotherbigNum;

//complete math operation
long l = largeOne * largeTwo;
if(l > Integer.MAX_SIZE){
    System.out.println("Overflow");
    //handle error
}

Should I be using a different primitive data type for these conversions, such as double?

Thanks in advance for your help

+1  A: 

You could check if the result is negative, or positive (depending on largeOne and largeTwo signs) but it would be a guess work.


I found another way, you could manually multiply your two numbers with an algorithm.


Resources :

On the same topic :

Colin Hebert
what happens when a double overflows? does it automatically become Inf? if so could that work?
Graham
In java a long or an int doesn't overflow, it wraps around, `MAX_SIZE + 1 == MIN_SIZE`
Colin Hebert
sorry wrapping around is what I meant
Graham
I think that the two ideas combined give a more secure result, but you can't really know for sure I'm afraid.
Colin Hebert
A: 

You could switch to using the BigDecimal class which has much better handling for overflow/underflow than the int/long primitives in Java. The int/long values are a special case that are not classes and as a result miss out on advantages of OOP.

Michael Shopsin
BifDecimal is not in CLDC, just in CDC.
Colin Hebert
I am working with J2ME, BigDecimal is only part of the Java Standard Ed.
Graham
Sorry, I'm using J2SE so I forgot what is omitted in J2ME.
Michael Shopsin