Result is undefined for percentage calculation in java

165 Views Asked by At

I want to calculate percentage and data here is completely dynamic.

int sample1 = 0;

int total = 0;

int finalValue = 0;

finalValue = ((sample1*100)/total)

Here finalValue is printed exactly as I want when there is some data. But When the value from database is 0(zero) then this simple calculation gives an error. If you perform calculation in calculator it says "Result is undefined". So in such case i tried using if and else condition.

if(sample1>0)
{
  //execute code
}
else
{
  //sample1 = 0;
}

This logic doesn't work here. So what would be easy and preferred way to perform percentage calculation.

3

There are 3 best solutions below

0
On BEST ANSWER

You should check total first .

Division by zero is not allowed and that's why it gives an error

if(total != 0)
{
  //execute code
}
else
{
 throw (err) ; // handle the division by zero error
}

Note : != means not equal to

0
On

You may exploit the fact that a double (as opposed to int) can represent undefined values:

    int sample1 = 0;
    int total = 0;
    double finalValue = 0;
    finalValue = ((sample1 * 100) / ((double) total));
    System.out.println(finalValue);

This prints:

NaN

which is short for “not a number”.

0
On
finalValue = ((sample1*100)/total)

You are dividing by zero.

So you'll have to check total first.

Or, if some data comes from a database, it could be null.