I am unable to format decimals and I am unsure why.

Discussion in 'Plugin Development' started by AoH_Ruthless, Mar 18, 2014.

Thread Status:
Not open for further replies.
  1. Offline


    I am trying to get a double and then damage the player using the double. Here is my code:

    double chance = (10 * (radius - 2)) / (radius) / 9; //Although it doesn't make a difference, 'radius' is an integer.
    DecimalFormat df = new DecimalFormat("#.##");
    chance = Double.valueOf(df.format(chance));
    Doing the math, 'chance' should be a value of 0.79 (Substituting 7 for radius) but instead it prints out 0.0. I thought it might be because the value starts with 0. So I added 1 to my algorithm for originally getting chance and now it printed out 1.0.

    Clearly, it's truncating the double. How do I fix it so that it doesn't truncate?
  2. Offline


    The rounding is happening because you're doing an integer division. When you divide two integers together, the result is an integer before you even do anything with it.
    1. System.out.println( 10 / 3 );
    2. System.out.println( 10 / 3.0 );
    3. System.out.println( 10 / (float)3 );
    Always cast the denominator (bottom one) to a float or double before doing a division.
    jthort likes this.
Thread Status:
Not open for further replies.

Share This Page