Reputation: 536
I am trying to get the nearest percent of two numbers in java, but it is not working.
This is what I have so far:
DecimalFormat df = new DecimalFormat("0.0");
double PD1 = (minus1 / MaxInt) * 100;
P1 = String.valueOf(df.format(PD1));
MaxInt is number possible, minus1 is MaxInt - 1 and then I multiply it by 100 to get the percentage and then the decimal format is suppose to round it to one decimal place, but it keeps returning a zero.
Upvotes: 1
Views: 2196
Reputation: 1126
Change it to:
double PD1 = ((double) minus1 / MaxInt) * 100;
For more explanation, take a look at this link on how to produce a double doing integer division in java.
Upvotes: 0
Reputation: 2691
First, your title says "Getting the percentage of two numbers to the nearest tenth in Java" while your text says "I am trying to get the nearest percent of two numbers"
Suppose variable double a = 12.34567;
represents a percentage (i.e. 12,34567%), to round it to the nearest tenth:
public class tst85 {
public static void main( String[] args)
{
double a = 12.34567;
double ar = Math.round(10.0*a)/10.0;
System.out.println(ar + " %");
}
}
This will print
12.3 %
For the nearest percent, just use Math.round
.
Upvotes: 2
Reputation: 864
You probably need to change it to something like this:
DecimalFormat df = new DecimalFormat("0.0");
double PD1 = (double)minus1/MaxInt * 100;
P1 = String.valueOF(df.format(PD1));
Basically, you need to cast your arguments, not your result. By the time you have done the operation, you will always get zero because an int divided by a bigger int is always zero.
Upvotes: 1