1

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
LUKER
  • 540
  • 1
  • 5
  • 23
  • 1
    http://stackoverflow.com/questions/7220681/division-of-integers-in-java – Reimeus Mar 16 '16 at 00:51
  • 3
    I'm going to assume `minus1` and `MaxInt` are integers. It won't work. You need to cast at least one value. Google dividing ints in java. – Ceelos Mar 16 '16 at 00:53
  • 1
    Here's a simple example.. http://www.coderanch.com/t/402257/java/java/nearest – AL. Mar 16 '16 at 00:55

3 Answers3

2

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.

Sci Prog
  • 2,651
  • 1
  • 10
  • 18
1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
privatestaticint
  • 854
  • 1
  • 9
  • 23
0

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.

Community
  • 1
  • 1
Ceelos
  • 1,116
  • 2
  • 14
  • 35