How to store infinity in a BigDecimal (Java)?

Viewed 10421

I am writing algorithms inside methods that return BigDecimal values but now and again the result calculated will be + or - infinity.
Rather than the program crashing I'd like to catch the exception and return infinity as a value like the way you could if the method was returning a double.

eg Double.POSITIVE_INFINITY;

So how do I store infinity in a BigDecimal? Or is there another way of doing this?

public static BigDecimal myalgorithm(){

//code to store infinity in a BigDecimal
//return the BigDecimal holding infinity 

}
2 Answers

An approach to the problem would be, to just use a really large number in this case:

BigDecimal.valueOf(negative ? Double.MIN_VALUE : Double.MAX_VALUE)

As BigDecimal does not have a real maximum or minimum value, you can use the ones of double.

Important with this approach is, that it doesn't really solve the problem of representing infinity, but depending on the usecase it can solve the problem well enough. I used it for the same usecase as you have mentioned above.

Actually double does more or less the same when calling intValue on it. In that case it will just represent the maximum integer.

Related