-4

I do not understand this. I tried the following:

    double procent = 0;
    int antalRätta = 5;
    int antalFela = 1;

    DecimalFormat df = new DecimalFormat("#.##");
    procent = (double) (antalRätta/(antalRätta+antalFela)) * 100;
    double procentMsg = Double.parseDouble(df.format(procent));

And procent prints out 0.0. Why?

Edit: If I change to double, I get:

Exception in thread "main" java.lang.NumberFormatException: For input string: "83,33"

Playdowin
  • 94
  • 1
  • 11

4 Answers4

0

The problem here is that you are making the sum of two integers and then casting. In order to format the number as you wish, you will have to cast the int to double before doing the sum...

EDIT

In order to avoid the exception you are getting, you will need to enter your value with a dot instead of a comma.

Aurasphere
  • 3,841
  • 12
  • 44
  • 71
  • Or you can supply the appropriate [`DecimalFormatSymbols`](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormatSymbols.html) for your Locale to the `DecimalFormat(String, DecimalFormatSymbols)` constructor... – JonK Nov 20 '15 at 16:58
0

because you should remove the bracket change this

 procent = (double) (antalRätta/(antalRätta+antalFela)) * 100;

with this

procent = (double) (antalRätta/antalRätta+antalFela) * 100;

you have 200 because

 antalRätta/antalRätta = 1
 and  1 + antalFela = 2
  2*100 = 200
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

Change your math code to this:

procent = ((double) antalRätta/(antalRätta+antalFela)) * 100;

That way when you do the integer division you cast the result to a double. Then when multiplying by 100 it doesn't matter since when we multiply a double and an integer we get back a double.

gonzo
  • 2,103
  • 1
  • 15
  • 27
0

When you divide an int, you will get an int: 5 / 6 = 0. Converting to double will primarily add one decimal place, i.e. 0.0 - that's it.

mrek
  • 1,655
  • 1
  • 21
  • 34