-2

I am using Java 7

I am trying to get a double from dividing two integer:

double chance = 1/main.getConfig().getInt("dailygiftItems.items."+key+".chance");
double w = Math.random();
System.out.println("Pulled: "+main.getConfig().getInt("dailygiftItems.items."+key+".chance"));
System.out.println("itemChance: "+chance);
System.out.println("itemRand: "+w);
if(!(w < chance))continue;

However chance is returning 0. As you can see I have debugged all the values here is what they bring me:

Pulled: 5

itemChance: 0

itemRand: some random double (working correctly)

I was thinking if I did my math wrong and 5/1 is not 0.2 so I used a calculator. However the calculator returned to me 0.2.

I then tested on something simpler testing the same problem:

public class Test
{

    public static void main(String[] args)
    {
        double chance = 1/5;
        double w = Math.random();
        System.out.println("Chance: "+chance);
        System.out.println("Random: "+w);
        if(!(w < chance))
        {
            System.out.println("no");
            return;
        }
        System.out.println("yes");
    }

}

This produced the same result as:

Chance: 0

w: some random double (working)

My questions: Why is java not dividing this correctly, and how can I fix it?

JarFile
  • 318
  • 2
  • 8
  • 30

1 Answers1

0

Use double chance = 1./main.getConfig().getInt("dailygiftItems.items."+key+".chance");

The . after 1 will force the compiler into considering this is a floating point (double) operation.

dotvav
  • 2,808
  • 15
  • 31
  • I would rather use `1d/` or `1.0/` or `(double) 1/`, although `1./` is valid it's very ugly to read – BackSlash Aug 04 '15 at 07:13
  • @BackSlash The only one that doesn't look ugly to me is `1.0`, but it's one more character to type :). Anyways, that's a matter of style and opinion. – dotvav Aug 04 '15 at 07:15