0

I want to calculate the value 0.95. Here is my method:

public static final int VAR = 5; 
private static double getDouble(){
        double dis = (double)(VAR/100);
        dis = (double)(1-dis);
        return dis;
}

However, it output 1.0?? If I type the same code in main method I got 0.95. Where is my mistake?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
sammy333
  • 1,384
  • 6
  • 21
  • 39
  • The result of an integer division will always be an integer. In your case, your integer is then being converted to a double, doing at @kocko recommends should fix the problem. – npinti Apr 06 '15 at 07:33
  • what is the datatype of `VAR` – singhakash Apr 06 '15 at 07:36

1 Answers1

6

(5/100) will return 0, which will be casted to double as 0.0.

Just do:

double dis = (5d/100);

Since you have declared VAR = 5, you have to cast it to double and then do the division:

double dis = ((double) VAR) / 100;
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147