Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a double is infinite in Java

Tags:

java

I'm making a simple calculator for this homework, and Java is returning "Infinity" when divided by 0.

I need to display some error message, when I get infinity. The problem is I don't know how to do the condition

double result; result = 4/0; //if result == infinity then some message - need help with this 
like image 651
Jacek Kwiecień Avatar asked Nov 29 '11 13:11

Jacek Kwiecień


People also ask

Is infinity a double in Java?

The Double class in Java supports infinity. You can implement positive infinity or negative infinity.

How do you find infinity value in Java?

The isInfinite() method of Java Float class returns a Boolean value for the specified float object or for 'v'. This method returns true if the argument passed is infinitely large in magnitude and returns false for finite floating-point arguments.

Is NaN double?

The IEEE Standard for Floating-Point Arithmetic (IEEE 754) defines the NaN value. In Java, the floating-point types float and double implement this standard. Java defines NaN constants of both float and double types as Float.


2 Answers

You can use Double.isInfinite(double)

Here's double doc

like image 168
soulcheck Avatar answered Sep 25 '22 14:09

soulcheck


The above code produces

ArithmeticException: / by zero 

You can catch this exception in a try/catch block.

like image 38
Peter Lawrey Avatar answered Sep 25 '22 14:09

Peter Lawrey